NuxtJS构建SPA部署Nginx服务器遇动态页面404错误求助
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:
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).Add the critical routing rule
Update yourserverblock to include alocation /directive that usestry_filesto route all requests toindex.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; } }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
- First, check if your config has any syntax errors:
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
rootpath points exactly to your uploadeddistfolder’s absolute path on the server (double-check this if you still get errors!).
内容的提问来源于stack exchange,提问作者Ahmad Abed

