Nginx 403 forbidden index html

How to Fix 403 Forbidden Error in NGINX Ubuntu

The 403 Forbidden error is the most common error encountered while working on Nginx web server. But most of the time, it is not related to Nginx itself. 403 Forbidden error means that you don’t have permission to access certain directory or a web page. This error can be caused due to many reason. And in this article we will identify the source of the error and then we will learn how to Fix it.

About 403 Error

Let’s understand “403 Forbidden” error in details.

“403 Forbidden” is an error which indicates that you have requested for something that NGINX cannot deliver. This error is actually an HTTP status code which simply means that the web server has received and understood the request which is made, but cannot process further.

4 Ways Fix 403 Forbidden Error

1. Wrong Directory or File permissions

Incorrect file permissions are one of the most common cause of this “403 Forbidden” error. In case of NGINX, the standard permission settings for directories and and file are 755 and 644 respectively. Moreover, the NGINX user also needs to be the owner of the directory and files.

Identify the NGINX User

To begin, we first need to identify the NGINX user. To check the user, run:

userwv+ 6016 26683 0 19:28 ttyS0 00:00:00 grep --color=auto nginx root 26734 1 0 Mar20 ? 00:00:00 nginx: master process /usr/sbin; www-data 26739 26734 0 Mar20 ? 00:01:53 nginx: worker process

In our case, we can identify the NGINX worker processe in the third row of the first column.

We can see that the NGINX worker process is running as the user www-data .

Set File Ownership

Since we already know that the standard permission for the directory in case of Nginx is 755 and that of the file is 644. We need to set the file ownership.

For example, if the root folder of your website is /var/www/html/example.com/public_html/ , run:

sudo chown -R www-data:www-data /var/www/html/example.com/public_html/

Set Directory Permissions

Now we need to set 755 permissions on each directory in this location.

sudo chmod 755 [directory name]

In our case, we need to set permission on example.com directory. To achieve that, run:

sudo chmod 755 example.com

Now, navigate to the root directory of the website by running:

Now change the file permission to 644 by running:

Читайте также:  Php check variable is class

2. Incorrect Index File

The “403 Forbidden” error can appear if the index file is not set properly.

Navigate to the NGINX configuration file and check whether you have updated correct index file or not. To do that, open our NGINX configuration file for example.com, by running:

sudo vim /etc/nginx/sites-available/example.com

For example, if you’re running a WordPress based website, inside the server block your index should be:

If you’re running an HTML based website, your default file must contain .html extension. e.g.,

Chances are there that you might have forgotten to add this line inside the server block. If you have included this line of code, you must check whether you have spelled it correctly or not.

Moreover, you also must keep in mind that these file names are case-sensitive. If the default file name is index.html but the file is named mentioned in NGINX configuration is Index.html, this will throw “403 Forbidden” error.

If you are running some web application that NGINX is not able to recognize, you can edit configuration file and add the file extension.

For example, if you’re running a python based application, you can add index.py to the list of recognized index files:

In case you’re running a web application that uses multiple programming languages, you can add:

index index.php index.html index.py;

Now, update the changes in the configuration file and restart NGINX by running:

sudo service nginx restart

Autoindex

It is an alternative solution which is useful if you don’t have any index file or no index file is found by NGINX.

The the server will scan and list all of the contents of your website’s root directory by autoindex method. But for security reasons, the directory index is turned off in NGINX by default.

You can turn on this feature by just adjusting a few lines of code. You just need to turn on and turn of the autoindex and autoindex_exact_size respectively.

autoindex on; autoindex_exact_size off;

Now you can add these configurations to the location block. The final result will look like:

To activate the directory indexing for some other directories, you can add the forward slash (/) and then the name of the directory. For example:

Now, save the changes and reload the NGINX.

3. Directory restrictions by IP

Inside your nginx.conf file, check if you have applied allow/deny rule that may be blocking your network. For example:

4. No index files

This could be a silliest mistake if you don’t have any file name as ‘index (index.php, index.html, index.py)’ inside the root directory of your website. This could also be a reason that your website is throwing a 403 Forbidden Error.

Additional Resources

You might also want to check some other fixes:

  • Error Establishing a Database Connection in WordPress Fix
  • Fix 502 Bad Gateway Nginx Error in Ubuntu
  • Fix: 504 Gateway Timeout Nginx Error
  • PHP5-FPM 502 Bad Gateway Error (connect() to unix:/var/run/php5-fpm.sock failed (2: No such file or directory)
  • Your PHP installation appears to be missing the MySQL extension which is required by WordPress
Читайте также:  Запрос json php примеры

I hope you these 4 ways will help you to Fix 403 Forbidden Error.

Which of these ways helped you get rid of this error? Let us know in the comment section below.

Источник

How to fix NGINX 403 Forbidden

When dealing with servers and web resources, we encounter errors that we cause when performing maintenance and configurations. When you encounter such errors, you need to diagnose and fix the problem as fast as possible to avoid downtime and data loss.

This quick guide will address a common error when working with NGINX servers (403 Forbidden), its causes, and how to fix it.

What is the Nginx 403 Error?

Nginx 403 Forbidden error is a status code generated and displayed to the user when a client tries to access a part of the webserver with insufficient permissions. For example, NGINX protects directory listing and will result in an error 403.

Server Side Causes of Nginx 403 Error

Before we get started, it is good to note that the error can come from the client-side and not the server itself. We shall address the server-side errors first, then client-side errors.

Cause 1: Incorrect Index File

The very first and common cause of the NGINX 403 Forbidden error is an incorrect configuration for the index file.

The Nginx configuration file specifies which index files to load and the order in which to load them. However, if the specified index files are not in the directory, Nginx will return 403 forbidden error.

For example, the config below defines the index files and how they should be loaded

One way to resolve this issue is to add the index file specified in the configuration file or add the available index file to the config file.

Another way to solve this issue is to allow Nginx to list directories if the index file is unavailable. Enable this module by adding the following entry to the configuration file.

NOTE: We do not recommend this method on publicly accessible servers.

For more information on how to serve static content, consider the Nginx documentation resource provided below:

Cause 2: Incorrectly set permissions

Nginx 403 forbidden error can also result from files and directories having incorrectly set permissions. For Nginx to successfully server a specific file and resource to the client, Nginx needs to have RWX—read, write and execute—permissions on the entire path.

To resolve this error, change the directories permission to 755 and the file permissions to 644. Ensure that the user running the Nginx process owns the files. For example, set user to www-data:

Finally, set the directory and file permissions as:

Client-Side Cause of Error 403

As mention, at other times, the 403 error may user-caused instead of being on the server-side. To resolve such issues on the client-side, perform the following operations.

  • Ensure you are accessing the correct web location
  • Clear browser cache
  • Ensure the firewall or proxy allows you to access the web resource.
Читайте также:  Execute python script from command line

Conclusion

This quick guide discussed the causes of the NGIX 403 forbidden error and various ways to fix it. It is good to look at the server logs before attempting any troubleshooting methods.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list

Источник

Решение проблем, связанных с ошибкой NGINX «403 Forbidden»

« 403 Forbidden » — наиболее распространенная ошибка при работе с NGINX . В этой статье мы расскажем о причинах возникновения 403 forbidden NGINX , а также о том, как найти ее причину и исправить основную проблему.

Об ошибке

« 403 Forbidden » — это универсальная ошибка NGINX , которая указывает на то, что вы запросили что-то, а NGINX ( по ряду причин ) не может это предоставить. « 403 » является кодом состояния HTTP , который означает, что веб-сервер получил и понял ваш запрос, но не может предпринять никаких дальнейших действий.

Поиск файла конфигурации NGINX

По умолчанию файлы конфигурации NGINX находятся в папке /etc/nginx . Если вы просмотрите этот каталог, то найдете несколько конфигурационных файлов для различных модулей сервера.

Главный файл конфигурации — /etc/nginx/nginx.conf . Он содержит основные директивы для NGINX и является аналогом файла httpd.conf для Apache .

Чтобы отредактировать этот файл, используйте команду:

CentOS 7: sudo nano /etc/nginx/conf.d/test.example.com.conf Ubuntu 16.04: sudo nano /etc/nginx/sites-available/test.example.com.conf

Некорректный индексный файл

Одна из наиболее распространенных причин ошибки 403 forbidden NGINX — некорректная настройка индексного файла.
nginx.conf указывает, какие индексные файлы должны загружаться, и в каком порядке. Например, приведенная ниже строка указывает NGINX искать index.html , затем index.htm , затем index.php :

index index.html index.htm index.php;

Если ни один из этих трех файлов не будет найден в каталоге, NGINX вернет ошибку « 403 Forbidden ».

Примечание . Имена файлов чувствительны к регистру. Если nginx.conf указывает index.html , а файл называется Index.html , это приведет к ошибке « 403 Forbidden ».

Если вы хотите использовать имя индексного файла, которое ваш веб-сервер NGINX не распознает, отредактируйте nginx.conf и добавьте имя файла в строку конфигурации индекса.

Например, чтобы добавить index.py в список распознаваемых индексных файлов, отредактируйте эту строку следующим образом:

index index.html index.htm index.php index.py;

Сохраните изменения, а затем перезапустите NGINX командой:

Автоиндекс

Альтернативным решением является разрешение индекса директории. Индекс директории означает, что если индексный файл не найден, сервер отобразит все содержимое директории.

По соображениям безопасности индекс директории в NGINX по умолчанию отключен.

При « 403 forbidden NGINX », если вы хотите показать индекс директории в ситуациях, когда NGINX не может найти ( идентифицировать ) файл, отредактируйте nginx.conf , как описано выше, и добавьте в него две следующие директивы:

Autoindex on; Autoindex_exact_size off;

Эти директивы должны быть добавлены в блок location . Можно либо добавить их в существующий блок location/ , либо добавить новый. Окончательный результат должен выглядеть так:

Также можно активировать индексирование директории в определенной папке, если не хотите, чтобы она была доступна для всего сайта:

Сохраните изменения в файле, затем перезапустите NGINX командой:

Источник

Оцените статью