Nginx多反向代理及Angular应用托管配置路径匹配异常问题求助
核心问题出在location ^~ /app/块内的try_files配置逻辑:
你当前配置的try_files $uri $uri/ /index.html;会在访问/app/login时,先检查是否存在对应/app/login的静态文件、目录,二者都不存在的话会触发Nginx内部重定向到/index.html。这个重定向后的请求路径是/index.html,不再匹配^~ /app/的前缀规则,所以会命中最后的location /,被转发到8087端口。
你对^~修饰符的理解没有问题,它确实会在匹配前缀成功后停止匹配其他正则location,但该场景下是内部重定向生成了新的请求,新请求重新走了一遍location匹配流程,才会命中根路径的转发规则。
另外存在一个次要可选优化点:当前/api/v1/的proxy_pass配置没有加尾斜杠,会把/api/v1/前缀也带到5000端口的服务请求里,比如访问/api/v1/user会被转发到http://localhost:5000/api/v1/user,如果你希望转发后去掉/api/v1/前缀,需要把proxy_pass改成http://localhost:5000/(末尾加斜杠)。
只需要修改/app/对应的location块,把fallback路径改成/app/index.html即可,确保内部重定向的路径依然匹配/app/前缀,不会落到根location规则里。
修改后的完整配置如下:
worker_processes 4; events { worker_connections 1024; } http { server { listen 80; root /usr/share/nginx/html; include /etc/nginx/mime.types; location ^~ /api/v1/ { # 如需转发时去掉/api/v1/前缀,末尾加斜杠即可:proxy_pass http://localhost:5000/; proxy_pass http://localhost:5000; } location ^~ /app/ { # fallback改成/app/index.html,保证重定向后仍匹配当前location规则 try_files $uri $uri/ /app/index.html; } location / { proxy_pass http://localhost:8087; } } }
修改后需要确保你的Angular打包后的所有静态资源都放在/usr/share/nginx/html/app目录下,也就是/usr/share/nginx/html/app/index.html文件存在即可正常运行。
内容的提问来源于stack exchange,提问作者Markos Stamatakis

