托管两个NextJs应用时Nginx第二条路由无法生效的问题
Nginx /admin/ 路由转发失效的解决方案
问题出在Nginx的location匹配优先级上:前缀匹配的/会匹配所有以/开头的请求(自然包括/admin/开头的),而Nginx默认会采用第一个匹配到的location规则,所以你的/admin/规则根本没机会被触发。
给你两种可行的修复方案:
方案1:用^~提升/admin/规则的优先级
^~修饰符会让这个location成为最长前缀匹配的优先规则,一旦请求路径匹配上,就不再去匹配其他前缀或正则规则。修改后的配置如下:
server { listen 80; server_name host_server; # 把/admin/规则放在前面,加上^~修饰符 location ^~ /admin/ { proxy_pass http://localhost:3001; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } location / { proxy_pass http://localhost:3000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } }
方案2:使用正则匹配/admin/路径
正则匹配的优先级高于前缀匹配,只要请求路径以/admin/开头,就会优先命中这个规则:
server { listen 80; server_name host_server; location ~^/admin/ { proxy_pass http://localhost:3001; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } location / { proxy_pass http://localhost:3000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } }
额外优化:处理不带斜杠的/admin请求
如果用户访问http://host_server/admin(不带末尾斜杠),上面的规则不会匹配。可以添加一个精准匹配的location做重定向:
location = /admin { return 301 /admin/; }
修改完成后,记得重载Nginx配置让修改生效:
sudo nginx -s reload
内容的提问来源于stack exchange,提问作者Senuda Jayalath
相关产品推荐
相关产品推荐

