如何配置Nginx负载均衡,使后端始终返回固定域名https://a.example.com?
解决方案
问题的核心是后端服务器b.example.com返回的响应中包含了自身域名(比如重定向的Location头或页面内硬编码链接),导致浏览器地址栏跳转或显示错误域名。通过Nginx负载均衡的响应改写能力即可解决,具体配置如下:
完整配置示例
upstream backends { server 172.20.1.2:443; #a.example.com server 172.20.2.2:443; #b.example.com } server { listen 80; server_name a.example.com; location / { proxy_pass https://backends; # 确保后端收到的Host头始终是a.example.com proxy_set_header Host a.example.com; # 传递真实客户端IP和请求协议给后端(可选但推荐) proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header X-Forwarded-Proto $scheme; # 改写后端返回的重定向Location头,替换b.example.com为a.example.com proxy_redirect https://b.example.com/ https://a.example.com/; proxy_redirect http://b.example.com/ https://a.example.com/; # 若后端页面内容中硬编码了b.example.com,替换为a.example.com sub_filter 'b.example.com' 'a.example.com'; sub_filter_once off; # 替换所有匹配项,而非仅第一个 } }
关键配置说明
proxy_redirect:专门处理后端返回的3xx重定向响应,将Location头中的b.example.com强制替换为a.example.com,确保浏览器收到的重定向地址始终是目标域名。sub_filter:如果后端返回的HTML、JS、CSS等内容中存在硬编码的b.example.com链接,该指令会自动替换为a.example.com,避免用户点击后跳转到错误域名。proxy_set_header Host:保持后端收到的请求Host头为a.example.com,减少后端返回自身域名重定向的可能性。
进阶:配置HTTPS服务(推荐)
如果需要负载均衡直接对外提供HTTPS服务,可补充以下配置,将80端口请求重定向到443:
# 80端口重定向到HTTPS server { listen 80; server_name a.example.com; return 301 https://$server_name$request_uri; } # HTTPS服务配置 server { listen 443 ssl; server_name a.example.com; # 替换为你的SSL证书路径 ssl_certificate /path/to/your/cert.pem; ssl_certificate_key /path/to/your/key.pem; location / { proxy_pass https://backends; proxy_set_header Host a.example.com; proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header X-Forwarded-Proto https; proxy_redirect https://b.example.com/ https://a.example.com/; proxy_redirect http://b.example.com/ https://a.example.com/; sub_filter 'b.example.com' 'a.example.com'; sub_filter_once off; } }
内容的提问来源于stack exchange,提问作者mocart
相关产品推荐
相关产品推荐

