Search code examples
http-redirecthaproxy

HAProxy redirect to subdomain


I am trying to redirect these:

to these:

But struggling with the documentation and the best way to do this.

* Update *

This is what I have got working at the moment. If I pass in:

then this redirects to:

... and the section of the config:

acl blog_page path_beg -i /blog
use_backend blog_site if blog_page
backend blog_site
reqrep        ^([^\ :]*)\ \/?(.*)\/blog\/?(.*)    \1\ /\2\3
redirect prefix http://blog.example.co.uk code 301

Solution

  • The following line in the frontend section will accomplish this rewrite and redirect.

    Shown as multiple lines for clarity, this must all appear on a single line of your configuration:

    http-request redirect 
            code 301 
            location https://blog.example.com%[capture.req.uri,regsub(^/blog,)]  
            if { hdr(host) -i www.example.com } { path_beg /blog }
    

    If the host header matches www.example.com and path begins with blog, redirect to a location beginning with the literal string https://blog.example.com then concatenate a value derived by taking the request URI (path + query string) and using regex substitution to remove /blog from the beginning.

    Verifying:

    $ curl -v 'http://www.example.com/blog/posts?which=this&that=1'
    * Hostname was NOT found in DNS cache
    *   Trying 127.0.0.1...
    * Connected to www.example.com (127.0.0.1) port 80 (#0)
    > GET /blog/posts?which=this&that=1 HTTP/1.1
    > User-Agent: curl/7.35.0
    > Host: www.example.com
    > Accept: */*
    >
    < HTTP/1.1 301 Moved Permanently
    < Content-length: 0
    < Location: https://blog.example.com/posts?which=this&that=1
    

    The redirect location appears to be correct.

    If you want to redirect http and https separately, you'd need two lines, each of them testing an additional condition to determine whether the original request was over http or https.

    Using the regsub() converter requires HAProxy 1.6+.