How to Fix Nginx 404 Not Found on Ubuntu 22.04
1. The Root Cause
The “Nginx 404 Not Found” error on Ubuntu 22.04 typically indicates Nginx cannot locate the requested resource, often because the configured root directive in the server block does not match the actual file path on the filesystem. This frequently occurs when the default index.nginx-debian.html file is absent from /var/www/html, or a new application’s files are placed in a different directory without updating the Nginx server block.
2. Quick Fix (CLI)
To immediately resolve common Nginx 404s by ensuring a default index.html exists in the standard web root with correct permissions:
# Create a basic index.html file in the default Nginx web root
sudo bash -c 'echo "<!DOCTYPE html><html><head><title>WebToolsWiz</title></head><body><h1>WebToolsWiz - Nginx is Working!</h1></body></html>" > /var/www/html/index.html'
# Set correct ownership for Nginx to access files
sudo chown -R www-data:www-data /var/www/html
# Set correct permissions (read for others, execute for directories)
sudo chmod -R 755 /var/www/html
# Restart Nginx to apply changes
sudo systemctl restart nginx
3. Configuration Check
Inspect your Nginx server block configuration to ensure the root and index directives are correctly defined.
File to Edit: /etc/nginx/sites-available/default (or your specific site configuration file, e.g., /etc/nginx/sites-available/your_domain.conf).
After editing, ensure a symlink exists in /etc/nginx/sites-enabled/.
Lines to Change:
Within the server { ... } block, locate and verify the following directives:
server {
listen 80 default_server;
listen [::]:80 default_server;
# Ensure this 'root' directive points to the absolute path of your website's files.
# For default Ubuntu installations, this is commonly /var/www/html.
root /var/www/html;
# Ensure 'index' lists your primary default file (e.g., index.html, index.php)
# in the order Nginx should try to find them.
index index.html index.htm index.nginx-debian.html;
# ... other configurations ...
location / {
# This directive is critical. It tells Nginx to try finding a file matching the URI,
# then a directory matching the URI. If neither is found, it returns a 404 error.
# Ensure it's present and correctly configured.
try_files $uri $uri/ =404;
}
}
Action: Confirm the root path accurately reflects where your website’s files are located, and that your main index file (e.g., index.html) is listed in the index directive. If changes are made, save the file.
4. Verification
After making any configuration changes, test the Nginx configuration syntax and reload the service. Then, use curl to confirm the website is accessible and returning a 200 OK status.
# Test Nginx configuration for syntax errors
sudo nginx -t
# If the test is successful, reload Nginx to apply changes without dropping connections
sudo systemctl reload nginx
# Use curl to check if the website is now accessible and returning content
curl http://localhost/