如何让Nginx响应React路由且对未处理路由返回404?
Nginx部署React应用:兼顾路由跳转与404返回的配置方案
问题背景
在Nginx后端部署React应用时,直接访问React路由(不是从根index.html页面导航进入)经常会出现404错误。常规的解决办法是在nginx.conf里加这段配置:
location / { try_files $uri /index.html; }
但这么做会废掉Nginx对不存在路由返回404的默认逻辑——所有没匹配上的路径都会跳转到index.html,没法真正返回404状态码。
有没有办法既能正常处理React路由,又能让未定义的路由返回404?
我试了下面的配置但没用:访问/route1返回404,访问不存在的路由反而返回500。
location / { root /usr/share/nginx/html; index index.html index.htm; set $fallback_file /null; if ($uri ~ /$) { set $fallback_file /index.html; } if ($uri ~ /route1$) { set $fallback_file /index.html; } try_files $uri /index.html; }
可行解决方案
方法1:显式匹配React路由(适合路由少的场景)
把React里已经定义的所有路由,在Nginx里逐个匹配,只给这些路由跳转index.html的权限,其他路径直接返回404。示例配置:
root /usr/share/nginx/html; index index.html; # 匹配React已定义的路由 location = / { try_files $uri /index.html; } location = /route1 { try_files $uri /index.html; } location = /route2 { try_files $uri /index.html; } # 静态资源直接返回,不经过路由判断 location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ { expires 1y; add_header Cache-Control "public, immutable"; } # 其他未匹配的路径直接返回404 location / { return 404; }
这种方式维护起来直观,不会影响静态资源的正常访问。
方法2:用map指令批量管理路由(适合路由多的场景)
如果React路由数量多,写一堆location块太麻烦,可以用Nginx的map指令提前定义允许跳转的路由列表,动态判断是否需要 fallback 到index.html:
# 定义允许跳转index.html的路由列表 map $uri $should_fallback { default 0; / 1; /route1 1; /route2 1; # 把所有React已定义的路由都加在这里 } server { root /usr/share/nginx/html; index index.html; location / { try_files $uri @fallback; } location @fallback { # 只有在允许列表里的路由,才跳转到index.html if ($should_fallback) { try_files /index.html =404; } # 不在列表里的直接返回404 return 404; } # 静态资源配置 location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ { expires 1y; add_header Cache-Control "public, immutable"; } }
你的配置失效原因
你设置的$fallback_file变量根本没用到——最后一行的try_files $uri /index.html;会直接忽略之前的变量,把所有没匹配到文件的请求都跳转到index.html。另外,/null不是有效的文件路径,Nginx找不到这个文件,所以访问不存在的路由时会返回500错误。
内容的提问来源于stack exchange,提问作者Yousef Hamza
相关产品推荐
相关产品推荐

