Seeing a 403 Forbidden error after modifying the root directory in the Nginx configuration can often be due to permission issues. Nginx, or the user it's running as, is likely unable to access the files at the new root directory due to insufficient file permissions or SELinux policies if you're running on a CentOS/RHEL-based system.
Here are steps to rectify the issue:
1. Check Permissions
Ensure the permissions on your new directory and the files within allow for reading by the Nginx user (usually nginx or www-data, depending on your Linux distribution).
-
Set the correct ownership:
sudo chown -R nginx:nginx /home/www/html
or if your Nginx is running as www-data:
sudo chown -R www-data:www-data /home/www/html
-
Ensure the directory permissions allow for browsing:
sudo chmod -R 755 /home/www
This sets the ownership to the Nginx user and permits others to read and execute files within /home/www, which is what you typically need for a web server.
2. Check for SELinux Issues
If you're on a distribution that uses SELinux (like CentOS or Fedora), SELinux may be blocking access. You can check if SELinux is enforcing with:
getenforce
-
If it returns Enforcing, SELinux may be part of your issue. You can temporarily set SELinux to permissive mode to test:
sudo setenforce 0
-
Then try accessing your site again. If it works, SELinux was blocking your access. To configure SELinux properly for this directory without disabling SELinux protection, restore the original context for the web content by applying the correct context to your custom directory:
sudo semanage fcontext -a -t httpd_sys_content_t '/home/www/html(/.*)?'
sudo restorecon -Rv /home/www/html
This tells SELinux that /home/www/html is a directory for valid web content.
3. Adjust Configuration If Needed
Ensure your configuration is correct and free of typos. Double-check the paths and configuration directives. Also, check if there are any conflicting configurations in other files, such as sites-enabled or additional configs included from nginx.conf.
4. Check Nginx Error Logs
Nginx's error logs can provide specifics about what's going wrong. Check them for any error messages related to access permissions or file paths. By default, you might find the logs at /var/log/nginx/error.log, but the path can differ based on your configuration.
sudo tail -f /var/log/nginx/error.log
Analyzing the output after attempting to access the website might give you a clue about the error's nature, pointing more specifically to permission issues, path issues, or configuration mistakes.
Make sure after every change that affects Nginx's operation to restart or reload Nginx:
sudo systemctl restart nginx
or
sudo systemctl reload nginx
Taking these steps should help you resolve the 403 Forbidden error you're encountering after changing the root directory in your Nginx configuration.