HAProxy配置需求:实现域名代理时保持浏览器URL不变
HAProxy配置需求:实现域名代理时保持浏览器URL不变
看起来你现在的配置实现的是URL重定向(浏览器地址栏会跟着改变),但你真正需要的是反向代理式的URL改写——让HAProxy在后台悄悄把请求转发到example.com/test,同时让浏览器始终显示test.example.com。我们来调整你的配置,解决这个问题:
调整后的完整配置
frontend tt bind *:80 bind *:443 ssl crt /etc/ssl/certs/ssl.pem mode http # HTTP自动转HTTPS,这个逻辑没问题,不会影响URL保持 http-request redirect scheme https unless { ssl_fc } default_backend ss backend ss mode http balance roundrobin option forwardfor http-request set-header X-Forwarded-Port %[dst_port] http-request add-header X-Forwarded-Proto https if { ssl_fc } # 提取子域名(比如从test.example.com中提取出test) http-request set-var(req.subdomain) req.hdr(host),lower,regsub(\.example\.com$,) if { hdr_end(host) -i .example.com } # 改写请求路径:将原路径拼到/subdomain/后(比如test.example.com/abc → example.com/test/abc) # 如果只需要固定转发到/test(忽略原路径),可以改成:http-request set-path /%[var(req.subdomain)] http-request set-path /%[var(req.subdomain)]%[path] if { var(req.subdomain) -m found } # 改写请求的Host头为example.com,让后端识别正确的站点 http-request set-header Host example.com if { var(req.subdomain) -m found } # 关键修正:处理后端返回的重定向,把Location中的example.com/test改回test.example.com # 避免后端跳转导致浏览器URL变化 http-response replace-header Location ^https://example\.com/(%[var(req.subdomain)])(.*) https://%[var(req.subdomain)].example.com\2 if { var(req.subdomain) -m found } option httpchk HEAD / HTTP/1.1\r\nHost: localhost server web1 example.com:80 check
核心调整说明
- 路径改写优化:原配置会直接替换掉用户访问的原路径,调整后可以保留子路径(比如
test.example.com/abc转发到example.com/test/abc),如果不需要保留原路径,直接用固定的set-path /%[var(req.subdomain)]即可。 - 后端重定向修正:这是你之前遗漏的关键环节——如果后端
example.com返回重定向响应(比如Location: https://example.com/test/xxx),浏览器会直接跳转到该地址,导致URL变化。通过http-response replace-header可以把这个地址替换回test.example.com/xxx,确保地址栏不变。 - 变量可读性优化:把原配置的
req.rewrite_example改成req.subdomain,更直观易懂,便于后续维护。
验证方法
- 重启HAProxy生效配置:
systemctl restart haproxy
- 用curl测试请求和响应头,确认逻辑正确:
curl -v https://test.example.com
你会看到:
- 请求的Host头是
example.com,请求路径是/test(或带原路径的/test/xxx) - 响应的Location头(如果存在)会显示
https://test.example.com/xxx,而非example.com/test/xxx - 浏览器地址栏始终保持
test.example.com
备注:内容来源于stack exchange,提问作者Fabio
相关产品推荐
相关产品推荐

