Skip to content

How to Fix 404 Page Not Found Nginx

DodaTech 1 min read

In this tutorial, you'll learn about How to Fix 404 Page Not Found Nginx. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

The Problem

You visit your site and get:

404 Not Found
nginx/1.24.0

Or checking the logs:

2024/03/15 10:30:00 [error] 1234#1234: *1 open() "/var/www/html/index.html" failed (2: No such file or directory)

Nginx cannot find the file at the path specified by the root directive. This happens when the file does not exist, the path is wrong, or Nginx lacks permission to read the directory.

Quick Fix

Step 1: Check the root directive

nginx -t

If the configuration is valid, inspect the root path in your server block:

server {
    listen 80;
    server_name example.com;
    root /var/www/example.com/public;
    index index.html;
}

Step 2: Verify the file exists

ls -la /var/www/example.com/public/index.html

If the file is missing, create it:

echo "<h1>Hello World</h1>" | sudo tee /var/www/example.com/public/index.html

Step 3: Check permissions

Nginx runs as the www-data user (or nginx on some systems). Ensure it can read the files:

sudo chown -R www-data:www-data /var/www/example.com
sudo chmod -R 755 /var/www/example.com

Step 4: Fix try_files for SPA routing

For single-page applications, add this to handle client-side routing:

location / {
    try_files $uri $uri/ /index.html;
}

If you are using symlinks, Nginx may not follow them by default:

disable_symlinks off;

Alternative Solutions

Use curl to test the exact response Nginx returns:

curl -I http://localhost/index.html
# Expected: HTTP/1.1 200 OK

Prevention

  • Always test Nginx config with nginx -t before reloading.
  • Place static files in the directory specified by root.
  • Use index index.html index.htm to set default files.
  • Check permissions after deploying new files.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro