You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NuxtJS构建SPA部署Nginx服务器遇动态页面404错误求助

Fixing SPA 404 Errors on Nginx for Dynamic URLs

Hey there! I’ve dealt with this exact headache plenty of times when deploying SPAs (like Vue, React, or Angular apps) to Nginx. The issue boils down to how Nginx handles requests vs. how your SPA’s client-side routing works. Let me walk you through the fix step by step.

Why This Happens

When you visit a dynamic URL (like /dashboard or /user/123), Nginx tries to look for a physical file or directory at that path on your server—but those paths don’t exist! Your SPA uses client-side routing, which means all routing logic lives in the index.html file, not on the server. Nginx doesn’t know to hand off the request to your SPA’s frontend router by default, so it throws a 404.

The Solution: Update Your Nginx Configuration

You need to tell Nginx to redirect all non-static requests to your SPA’s index.html file. Here’s how to do it:

  1. Locate your Nginx site configuration
    It’s usually stored in one of these directories:

    • /etc/nginx/sites-available/ (then linked to /etc/nginx/sites-enabled/)
    • /etc/nginx/conf.d/

    Open your site’s config file with a text editor (e.g., sudo nano /etc/nginx/sites-available/your-spa.conf).

  2. Add the critical routing rule
    Update your server block to include a location / directive that uses try_files to route all requests to index.html. Here’s a complete example config:

    server {
        listen 80;
        server_name your-domain.com; # Replace with your domain/server IP
    
        # Path to your uploaded dist folder
        root /var/www/your-spa/dist;
        index index.html index.htm;
    
        # Serve static assets directly (caching them for better performance)
        location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
            expires 1y;
            add_header Cache-Control "public, immutable";
        }
    
        # Key fix: Send all other requests to index.html for client-side routing
        location / {
            try_files $uri $uri/ /index.html;
        }
    }
    
  3. Validate and restart Nginx

    • First, check if your config has any syntax errors:
      sudo nginx -t
      
    • If you see the message test is successful, restart Nginx to apply the changes:
      sudo systemctl restart nginx
      

Quick Notes

  • This works for history mode routing (the clean, hash-free URLs you’re probably using). If you were using hash mode (URLs with #), you wouldn’t hit this issue—but history mode is much more user-friendly.
  • Make sure the root path points exactly to your uploaded dist folder’s absolute path on the server (double-check this if you still get errors!).

内容的提问来源于stack exchange,提问作者Ahmad Abed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:28:19