将所有根域请求重定向到www。子域名,保持URL不变

时间:2017-01-04 20:41:36

标签: haproxy

我想将所有流量重定向到根域到www。版本仍然保持路径/查询字符串完整,我该怎么办?我已经设置了如下的HAproxy配置:

frontend http
        bind *:80
        bind *:443

        acl has_www hdr_beg(host) -i www
        http-request redirect code 301 location http://www.%[hdr(host)]%[req.uri] unless has_www

但是,这个会执行以下操作:example.com/abc?page=1 => www.example.com,我实际上不想这样做:example.com/abc?page=1 => www.example.com/abc?page=1 - 我错过了什么?

2 个答案:

答案 0 :(得分:1)

如果你正在使用HAProxy 1.5及以上,这应该适合你

单个域名

acl has_www hdr_beg(host) -i www
redirect prefix http://www.example.com code 301 unless has_www

多个域名(脏但有效)

# match non www requests:
acl has_www      hdr_beg(host) -i www.

# add a header that says we need to redirect these type of requests (will explain later)
http-request add-header X-Host-Redirect yes unless has_www

# rule to identify newly added headers
acl www_redirect hdr_cnt(X-Host-Redirect) eq 1

# where the magic happens (insert www. in front of all marked requests)
reqirep ^Host:\ (.*)$ Host:\ www.\1 if www_redirect

# now hostname contains 'www.' so we can redirect to the same url
  redirect scheme http if www_redirect

我们添加新标头的原因是因为看起来在HAProxy 1.5及更高版本中,acls正在每个引用上进行评估。因此,当您尝试在没有新标题的情况下执行此操作时,它会执行此操作:

#catch all domains that begin with 'www.'
acl has_www      hdr_beg(host) -i www.
#insert www. in front of all non www requests
reqirep ^Host:\ (.*)$ Host:\ www.\1 unless has_www
#now hostname contains 'www.' so when the next rule gets interpreted it does not match then fails  
#redirect to new url
redirect code 301 prefix / if has_www
希望这会有所帮助。我已经在HAProxy 1.5上用5个不同的域测试了它,它工作正常并且在重定向上保持查询字符串完整

答案 1 :(得分:0)

HAProxy 1.6的多域解决方案,重定向保留路径和查询参数:

frontend 443
  http-request redirect prefix https://www.%[hdr(host)] code 301 unless { hdr_beg(host) -i www. }