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

Nginx反向代理配置:如何返回网站主机URL而非API URL

解决Nginx反向代理后返回API域名而非网站域名的问题

你的问题核心是后端API返回的响应内容里自带了它自身的域名api.example.com,需要替换为网站域名app.example.com。可以通过Nginx的sub_filter模块实现响应内容的替换,调整后的配置如下:

location /api/1 {
        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 https;
        proxy_set_header X-Forwarded-Port 443;
        proxy_set_header Connection 'upgrade'; # 修正原配置里的拼写错误updgrade
        proxy_set_header Host $host;
        proxy_pass https://api.example.com/rest;
        proxy_ssl_server_name on;

        # 添加域名替换相关配置
        sub_filter 'api.example.com' 'app.example.com';
        sub_filter_once off; # 替换响应中所有出现的目标域名,而非仅第一次
        sub_filter_types *; # 对所有类型的响应内容生效(如JSON、XML、HTML等)
}

额外说明:

  • 先确认你的Nginx编译时包含了ngx_http_sub_module模块,执行nginx -V查看输出,若有--with-http_sub_module则说明已包含;若没有,需要重新编译Nginx并添加该模块。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 18:26:17