Nginx配置问题:无法同时部署Angular SPA与本地API服务
解决Nginx转发API时的404问题
你的404错误核心是Nginx的proxy_pass路径匹配规则没搞对,结合你的场景(API运行在8000端口根路径),给你两个靠谱的调整方案:
方案一:给proxy_pass加末尾斜杠(推荐)
修改location /api/块的proxy_pass配置,在目标地址后加斜杠:
server { listen 80; location / { root /var/www/html; try_files $uri $uri/ /index.html; index index.html; } location /api/ { proxy_pass http://localhost:8000/; # 关键:这里加了末尾斜杠 proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_cache_bypass $http_upgrade; } error_log /var/log/nginx/error.log debug; }
原理:当location路径带末尾斜杠,且proxy_pass也带末尾斜杠时,Nginx会自动去掉匹配的/api/前缀,把剩余路径转发到API的根路径。比如访问/api/user,实际转发到http://localhost:8000/user,正好匹配你的API服务。
方案二:用rewrite去掉前缀
如果不想依赖斜杠的匹配规则,可以用rewrite指令手动剥离/api前缀:
location /api { rewrite ^/api(.*)$ $1 break; # 把/api开头的路径替换成后面的部分 proxy_pass http://localhost:8000; # 以下proxy配置保留原样 proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_cache_bypass $http_upgrade; }
原理:rewrite规则会把/api/user转换成/user,再转发到8000端口,同样能正确匹配API。
为什么你之前的尝试没用?
- 移除
location /api/的末尾斜杠后,proxy_pass http://localhost:8000会把完整的/api/user转发到http://localhost:8000/api/user,但你的API没有/api前缀,所以返回404。 - 你提到的
proxy_pass http://localhost:8000$request_uri也不对,因为$request_uri包含完整的/api/user,转发后还是http://localhost:8000/api/user,依然匹配不到API。
验证步骤
- 修改配置后,先执行
nginx -t检查语法是否正确,确保没有报错。 - 执行
nginx -s reload重启Nginx,让新配置生效。 - 再次测试访问
http://{my-ip}/api/{my-resourse-name}。
内容的提问来源于stack exchange,提问作者Prozrachniy
相关产品推荐
相关产品推荐

