当路由使用 History 模式时,如何配置 Nginx 回退到 index.html?
解读
在国内前后端分离架构中,Apache Struts 2 通常只负责 REST 接口,而静态资源和单页(SPA)由 Nginx 直接托管。
History 模式去掉 # 后,浏览器刷新或深度跳转时,路径如 /order/123 会被 Nginx 当成真实目录,导致 404。
面试官想确认两点:
- 你清楚 History 模式与 Hash 模式的差异;
- 你能在 Nginx 层 给出零运维、可灰度、对 SEO 友好的回退方案,且不影响 Struts 的 REST 接口。
知识点
- History 模式依赖 pushState API,URL 变化不触发服务器请求,刷新时才会。
- Nginx 的
try_files指令按顺序检查文件/目录,最后一个参数就是回退地址。 - 必须先放行 Struts 的 REST 前缀(如
/api),否则会把接口也重写到index.html。 - 国内云厂商(阿里云、腾讯云)默认使用 tengine 2.3+,完全支持
try_files,无需编译第三方模块。 - 回退后 SPA 要配合
<base href="/">和 Struts 的struts.action.extension不覆盖静态路径,否则会出现二次 404。
答案
生产级配置示例(假设 SPA 文件在 /usr/share/nginx/html,Struts 接口统一 /api):
server {
listen 80;
server_name app.example.com;
# 1. 日志格式加响应时间,方便排障
access_log /var/log/nginx/app.access.log main;
# 2. 先放行 Struts 接口,避免被 try_files 吃掉
location ^~ /api/ {
proxy_pass http://struts_backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
# 3. 静态资源强缓存,减轻后端压力
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff2?)$ {
root /usr/share/nginx/html;
expires 1y;
add_header Cache-Control "public, immutable";
}
# 4. 所有非资源请求回退到 index.html
location / {
root /usr/share/nginx/html;
try_files $uri $uri/ /index.html;
# 关键点:index.html 本身必须存在,否则 500
}
# 5. 错误页兜底,防止暴露 nginx 版本
error_page 404 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
验证步骤:
nginx -t无报错后nginx -s reload;- 浏览器访问
https://app.example.com/order/123,刷新应 200; curl -I https://app.example.com/api/user/1应 200 且Content-Type: application/json,确保接口未被重写。
拓展思考
- 灰度发布:利用 Nginx
map指令按 Cookie 或 Header 分流,老用户走 Hash 模式,新用户走 History 模式,零回滚风险。 - SSR 兼容:若后续引入 Nuxt.js 服务端渲染,可把
try_files改为proxy_pass到 Node 层,Struts 与 SSR 并存。 - 安全加固:在
location /内再加add_header X-Frame-Options DENY;和Content-Security-Policy,防止点击劫持,满足国内金融等保 2.0 要求。