You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

通过Nginx代理Express API时出现404错误的排查求助

问题

搭建了一台使用Nginx的服务器,用于部署React应用并将请求反向代理至Express API。Nginx配置片段如下:

server {
    server_name example.com;

    root /var/www/example.com/html;
    index index.html;

    location / {
        try_files $uri $uri/ /index.html;
    }

    location /api/ {
        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;
    }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

访问https://example.com/api/posts时收到404 Not Found错误,但在服务器上直接访问http://localhost:3001/api/posts能正常返回数据。

Nginx访问日志片段:

192.168.1.1 - - [27/Jun/2024:12:34:56 +0000] "GET /api/posts HTTP/1.1" 404 144 "https://example.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.0.0 Safari/537.36"

已完成以下验证:

  • Express服务器正常运行并监听3001端口
  • Express已正确定义/api/posts路由
  • 修改配置后已重启Nginx
  • 无防火墙规则阻止连接

需分析该404错误的原因并提供解决建议。

原因分析及解决建议

核心原因

Nginx的proxy_pass配置末尾添加了斜杠/,导致请求路径被Nginx重写:
当请求https://example.com/api/posts时,Nginx会剥离路径中的/api/前缀,将请求转发至http://localhost:3001/posts,但你的Express路由定义的是/api/posts,因此找不到对应路由返回404。

解决方法

修改location /api/块中的proxy_pass配置,去掉末尾的斜杠:

location /api/ {
    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;
}

验证步骤

  • 执行nginx -t检查配置文件语法是否正确
  • 执行systemctl reload nginx(根据系统环境选择对应重启命令)使新配置生效
  • 再次访问https://example.com/api/posts确认请求是否正常返回数据

内容的提问来源于stack exchange,提问作者Aqu1tain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 19:19:58