When you’re encountering a 404 error with Nginx while trying to reload a single-page application (SPA), it’s usually because Nginx is not properly configured to serve the index.html file for all routes. In an SPA, the routing is typically handled client-side by the application itself, which means all routes should be directed to the index.html file.

Here’s how you can configure Nginx to handle this:

  1. Open your Nginx configuration file: This is usually located at /etc/nginx/nginx.conf or in a site-specific configuration file in /etc/nginx/sites-available/.
  2. Update the configuration: Ensure that Nginx redirects all requests to the index.html file for your SPA. Here’s an example configuration:
server {
    listen 80;
    server_name yourdomain.com;

    root /path/to/your/spa;  # Adjust this to the path where your SPA's files are located

    location / {
        try_files $uri $uri/ /index.html; # here will resolve 404 error when reload url
    }

    location /api/ {
        proxy_pass http://backend_server;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    error_page 404 /index.html;

    location ~* \.(?:manifest|appcache|html?|xml|json)$ {
        expires -1;
        add_header Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
    }

    location ~* \.(?:css|js|woff2?|ttf|eot|otf)$ {
        expires 1y;
        add_header Cache-Control 'public';
        add_header Pragma 'public';
    }

    location ~* \.(?:png|jpg|jpeg|gif|ico|svg|webp)$ {
        expires 1y;
        add_header Cache-Control 'public';
        add_header Pragma 'public';
    }
}

Explanation:

  • root: Defines the root directory of your application.
  • location /: This block handles all requests. try_files $uri $uri/ /index.html; tries to serve the requested file first. If it doesn’t exist, it falls back to serving index.html.
  • error_page 404 /index.html: This ensures that any 404 errors are redirected to index.html.
  • location /api/: This is an example for routing API calls to a backend server. Adjust it according to your setup.
  • location blocks for static files: These handle caching for various file types. Adjust as needed.
  1. Restart Nginx: After updating the configuration, restart Nginx to apply the changes:
sudo systemctl restart nginx

This configuration should help serve your SPA correctly and handle route refreshes without encountering 404 errors.