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

Nginx反向代理无需尾斜杠配置问题求助

Nginx反向代理无尾斜杠访问重定向问题解决

你的问题出在Nginx对请求URI的转发逻辑和重定向处理上,按照以下配置修改即可解决:

修正后的完整配置

server {
    listen 80;
    server_name localhost;

    location ^~ /central {
        # 提取/central后的路径部分,转发到Apache根路径
        rewrite ^/central(.*)$ $1 break;
        proxy_pass http://central;
        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-Host $server_name;
        
        # 修正Apache返回的重定向,确保路径前缀正确
        proxy_redirect http://central/ http://localhost/central;
        proxy_redirect http://central/api/ http://localhost/central/api;
    }

    location ^~ /microservices {
        rewrite ^/microservices(.*)$ $1 break;
        proxy_pass http://microservices;
        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-Host $server_name;
        
        proxy_redirect http://microservices/ http://localhost/microservices;
        proxy_redirect http://microservices/api/ http://localhost/microservices/api;
    }
}

关键调整说明

  1. rewrite规则提取路径:
    通过rewrite ^/central(.*)$ $1 break;把/central/api转换成/api后再转发,确保Apache收到的路径和直接访问时一致,避免路径不匹配导致的重定向。

  2. 移除proxy_pass尾斜杠:
    配合rewrite规则,确保转发路径准确,不会出现多余的拼接或缺失。

  3. proxy_redirect修正重定向:
    当Apache对不带尾斜杠的目录请求返回301重定向时,Nginx会自动修正重定向的URL前缀,把http://central/api/转换成http://localhost/central/api,避免跳转到错误的localhost/central/路径。

额外提示

修改后执行nginx -s reload重启服务,确保配置生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 23:18:33