Haproxy 更改 url 的一部分

Hug*_*ues 6 haproxy

我有一个重命名的应用程序,我希望 Haproxy 重定向到正确的路径,同时保留请求参数

这就是我所拥有的:

acl old_name path_dir -i /old_name
   http-request set-path /new_name/%[query] if old_name
Run Code Online (Sandbox Code Playgroud)

我希望它从

www.site.com/old_name/Default.aspx?Id=123
Run Code Online (Sandbox Code Playgroud)

www.site.com/new_name/Default.aspx?Id=123 but this is not working. 
Run Code Online (Sandbox Code Playgroud)

小智 12

使用 HAProxy 1.5 :使用临时标头从请求中的现有路径构建新路径,然后直接执行重定向

# Clean the request and remove any existing header named X-Rewrite
http-request del-header X-REWRITE

# Copy the full request URL into X-Rewrite unchanged
http-request add-header X-REWRITE %[url] if { path_beg /old_path }

# Change the X-REWRITE header to contain out new path
http-request replace-header X-REWRITE ^/old_path(/.*)?$ /new_path\1 if { hdr_cnt(X-REWRITE) gt 0 }

# Perform the 301 redirect
http-request redirect code 301 location http://%[hdr(host)]%[hdr(X-REWRITE)] if { hdr_cnt(X-REWRITE) gt 0 }
Run Code Online (Sandbox Code Playgroud)

在 HAProxy 1.6 中,使用 regsub 过滤器

http-request redirect code 301 location http://%[hdr(host)]%[url,regsub(^/old_path,/new_path,)] if { path_beg /old_path }
Run Code Online (Sandbox Code Playgroud)

以及其他有用的配置片段

有关regsub 关键字HAProxy 文档中提供了更多信息。

  • @flint 在逐字复制您在互联网上找到的内容时,您至少应该对 [来源](https://gist.github.com/meineerde/11865802f8338b18f123)(在这种情况下是我)添加一些归属。 (2认同)

小智 6

您将url 重定向url 重写到后端混淆了。

如果您甚至想重写,那么根据 haproxy 1.6 文档:

  • “set-path”用格式 string 的评估结果重写请求路径。查询字符串(如果有)保持不变。

所以在这种情况下正确的配置是:

acl old_name path_dir -i /old_name
http-request set-path /new_name if old_name
Run Code Online (Sandbox Code Playgroud)

重定向用户:

redirect location /new_name if old_name
Run Code Online (Sandbox Code Playgroud)