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

将Nginx配置为反向代理时遇301重定向问题求助

问题解决方法

原因分析

你的Nginx配置中location /hindiscript/是带尾斜杠的,当访问/hindiscript(不带尾斜杠)时,Nginx会触发301重定向,试图将请求转向带尾斜杠的路径;另外Node.js服务如果收到不带尾斜杠的请求,也可能返回301重定向。

修复方案

可通过以下两种方式解决:

方案1:统一匹配带/不带尾斜杠的请求

修改location块,同时兼容两种路径格式,并确保请求路径正确传递给Node服务:

server {
  listen 80;
  listen [::]:80;
  
  server_name example.com;
  root /var/www/example.com;
  index index.html;
  
  location /hindiscript {
        # 移除多余尾斜杠,统一请求路径格式
        rewrite ^/hindiscript(/.*)?$ $1 break;
        proxy_pass http://localhost:7778;
  }
  
  location /{
   try_files $uri $uri/ =404;
  }
}

方案2:重定向不带尾斜杠的请求到带尾斜杠路径

保留原有/hindiscript/配置,新增一个精准匹配不带尾斜杠路径的规则,主动重定向:

server {
  listen 80;
  listen [::]:80;
  
  server_name example.com;
  root /var/www/example.com;
  index index.html;
  
  location = /hindiscript {
        return 301 $uri/;
  }
  
  location /hindiscript/ {
        proxy_pass http://localhost:7778;
  }
  
  location /{
   try_files $uri $uri/ =404;
  }
}

验证步骤

修改配置后,执行以下命令重启Nginx:

sudo systemctl restart nginx

再次执行curl http://example.com/hindiscript,检查是否能正常访问Node服务返回的内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 14:30:49