How to Fix Permission Denied Error in Nginx
The
permission denied error in Nginx usually happens because Nginx lacks access rights to the files or directories it needs. Fix this by setting correct ownership (usually www-data) and permissions (like 755 for directories and 644 for files) on your web content and configuration files.Why This Happens
Nginx runs under a specific user (often www-data or nginx) and needs permission to read files and directories it serves. If these permissions are too strict or ownership is incorrect, Nginx cannot access them, causing a permission denied error.
nginx
server {
listen 80;
server_name example.com;
root /var/www/html;
index index.html;
}Output
2024/04/27 12:00:00 [crit] 1234#0: *1 open() "/var/www/html/index.html" failed (13: Permission denied), client: 192.168.1.10, server: example.com, request: "GET / HTTP/1.1", host: "example.com"
The Fix
Change ownership of your web files to the Nginx user and set proper permissions. Directories should be 755 and files 644. This lets Nginx read files without giving too many rights.
bash
sudo chown -R www-data:www-data /var/www/html sudo find /var/www/html -type d -exec chmod 755 {} \; sudo find /var/www/html -type f -exec chmod 644 {} \;
Prevention
Always set correct ownership and permissions when deploying files. Use automation scripts or deployment tools to keep permissions consistent. Avoid giving 777 permissions as it is insecure. Regularly check Nginx error logs to catch permission issues early.
Related Errors
- 403 Forbidden: Often caused by similar permission issues or missing index files.
- Failed to bind to port: Happens if Nginx lacks rights to use ports below 1024.
- SELinux denial: On systems with SELinux, permissions might be denied despite correct ownership; use
setenforce 0to test or configure SELinux policies.
Key Takeaways
Nginx needs proper ownership and permissions to access files and directories.
Set directories to 755 and files to 644 permissions for safe access.
Use the Nginx user (usually www-data) as owner of web content.
Avoid overly permissive settings like 777 to keep your server secure.
Check error logs regularly to spot permission problems early.