How to Fix Nginx Permission Denied on Ubuntu 22.04


The Root Cause

On Ubuntu 22.04, Nginx typically runs as the www-data user and group by default. The “Permission Denied” error occurs when the www-data user lacks the necessary read or execute permissions for the web root directory or the files within it, often because the site’s directories were created by another user (e.g., root or a deployment user) with restrictive permissions.

Quick Fix (CLI)

First, identify your web root directory (e.g., /var/www/html or a custom path defined in your Nginx configuration). Replace /path/to/your/website with your actual web root.

# Change ownership of the web root to www-data:www-data
sudo chown -R www-data:www-data /path/to/your/website

# Set directory permissions to 755 (owner R/W/X, group R/X, others R/X)
sudo find /path/to/your/website -type d -exec chmod 755 {} +

# Set file permissions to 644 (owner R/W, group R, others R)
sudo find /path/to/your/website -type f -exec chmod 644 {} +

# Restart Nginx to apply changes
sudo systemctl restart nginx

Configuration Check

1. Nginx Main Configuration: Verify that Nginx is configured to run as the www-data user. Edit the main Nginx configuration file:

sudo nano /etc/nginx/nginx.conf

Ensure the user directive at the top of the file is set correctly:

user www-data;
worker_processes auto;
# ... other configurations

2. Specific Server Block (if applicable): If you are using a custom root directory in a server block, ensure the path is correct and accessible. Check your site-specific configuration file (e.g., /etc/nginx/sites-available/your_domain.conf):

server {
    listen 80;
    server_name your_domain.com www.your_domain.com;

    # Ensure this path is correct and matches the directory permissions set above
    root /path/to/your/website; 
    index index.html index.htm index.nginx-debian.html;

    # ... other configurations
}

Verification

After applying the quick fix and checking configurations, verify that Nginx is running and serving content correctly.

1. Check Nginx Service Status:

sudo systemctl status nginx

The output should show Active: active (running).

2. Test Website Access:

curl http://localhost

or, if accessing from a browser, navigate to your domain or server IP address. If the issue is resolved, you should see the content of your web root’s index file (e.g., index.html) or the expected web application output.

3. Check Nginx Error Logs (if issue persists):

sudo tail -f /var/log/nginx/error.log

This command will display real-time error messages, which can provide further clues if the “Permission Denied” error persists or a new issue arises.