haproxy重写策略主要通过http-request set-path、set-header和redirect实现,涵盖路径改写、host头替换及强制跳转三类场景,效果等同nginx rewrite但术语不同。

HAProxy 的重写策略主要通过 http-request set-path、http-request set-header、redirect 等指令实现,适用于 URL 路径改写、Host 头替换、协议/域名强制跳转等场景。它不叫“重写”(rewrite)而更常称“路径修改”或“请求重定向”,但效果等同于 Nginx 中的 rewrite。
以下是最常用、最实用的三类重写策略配置方式:
1. 修改请求路径(set-path)
用于统一前缀、去除冗余路径、或适配后端服务路径要求。
frontend http_in
bind *:80
# 将 /api/v1/xxx → /v1/xxx
http-request set-path %[path,map_reg(/etc/haproxy/path-rewrite.map)]
# 或直接正则替换(需 HAProxy ≥ 2.0)
http-request set-path /v1%[path,regsub(^/api/v1/,)]
default_backend app_servers
✅ 注意:
map_reg需提前准备映射文件/etc/haproxy/path-rewrite.map,格式如:/api/v1/ /v1//static/ /assets/
FastAPI Flask Proxy下载FastAPI + Flask 混合部署最佳实践,解决路由定义、API 代理等常见问题,适用于同时运行 FastAPI API 与 Flask 前端的场景。
2. 替换 Host 请求头(set-header)
常用于多租户或反向代理中,让后端看到指定域名而非真实访问域名。
backend app_servers
mode http
option forwardfor
http-request set-header Host www.example.com
server app1 192.168.1.10:8080 check
server app2 192.168.1.11:8080 check
⚠️ 若后端依赖 Host 判断路由(如 Spring Cloud Gateway),此项必不可少。
3. 强制重定向(redirect)
这是最常用的“重写”类操作,包括 HTTP→HTTPS、域名标准化、路径跳转等。
frontend http_in
bind *:80
# 强制跳 HTTPS
redirect scheme https code 301 if !{ ssl_fc }
# 去掉 www(www.example.com → example.com)
acl has_www hdr(host) -i www.example.com
redirect code 301 location https://example.com%[capture.req.uri] if has_www
# 统一末尾不带斜杠(/foo/ → /foo)
acl ends_with_slash path_reg /\/$/
redirect code 301 location %[path,regsub(/\/$,,)] if ends_with_slash
frontend https_in
bind *:443 ssl crt /etc/haproxy/certs/example.com.pem
# 所有请求加 /v2 前缀再转发
http-request set-path /v2%[path]
default_backend api_v2
✅
redirect支持code 301/302、location(绝对路径)、prefix(相对路径)等多种模式;
✅%[path]、%[capture.req.uri]是常用变量,可组合使用;
✅ 正则替换用regsub(),注意转义和空格处理。
不复杂但容易忽略











