页面刷新 404 问题,一般出现在 前端单页应用(SPA,Vue/React/Angular) 部署到 Nginx 时。
原因是:
- Nginx 默认只会返回真实存在的文件。
- 刷新时,浏览器会请求
http://domain.com/some/path,Nginx 去找对应的文件夹和文件,找不到就返回 404。 - 但 SPA 其实是依赖前端路由,所有路径都应该交给
index.html处理。
解决方法:在 Nginx 配置中增加 try_files 回退到 index.html
例如:
server {
listen 80;
server_name yourdomain.com;
root /usr/share/nginx/html; # 前端打包后的目录
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
# 可选:静态资源缓存优化
location ~* \.(?:ico|css|js|gif|jpe?g|png|woff2?|eot|ttf|svg)$ {
expires 6M;
access_log off;
add_header Cache-Control "public";
}
}
原理
-
try_files $uri $uri/ /index.html;$uri:先找是否有对应文件$uri/:再找是否有目录/index.html:如果都没有,返回index.html
这样,当用户刷新 /users/123 时,Nginx 会返回 index.html,前端路由再去解析。
⚠️ 注意
index.html必须存在于root指定的目录下。- 如果有 API 接口,比如
/api/**,需要单独配置,不要被重定向到index.html,比如:
location /api/ {
proxy_pass http://127.0.0.1:8080; # 后端服务
}
2355

被折叠的 条评论
为什么被折叠?



