HAProxy – Redirect Non-WWW to WWW with SSL

haproxy

What I want to achive are redirects:

http://test.com --> https://www.test.com
http://www.test.com/ -> https://www.test.com
https://test.com --> https://www.test.com

My current haproxy conf:

global
    log 127.0.0.1 local0 notice
    maxconn 3000
    user haproxy
    group haproxy
    daemon

defaults
    log     global
    mode    http
    option  httplog
    option  dontlognull
    retries 3
    option redispatch
    timeout connect  5000
    timeout client  5000
    timeout server  5000

frontend http-in
    bind *:80
    bind *:443 ssl crt /etc/letsencrypt/live/www.test.com/www.test.com.pem
    mode http
    http-request redirect prefix https://www.%[hdr(host)] code 301 if { hdr(host) -i test.com }   /// THIS DOESN'T WORK

    option forwardfor
    redirect scheme https code 301 if !{ ssl_fc }
    .
    .
    .

My Problems:

https://test.com and http://test.com don't redirect to
https://www.test.com

Do I need a ssl cert for https://test.com ? If yes, how do I add this into the haproxy conf?

Best Answer

The redirect command that you have there just redirects from http to https - it does not manipulate any other part of the URL, so the behavior you see is expected.

For the HTTP -> HTTPS redirect, you probably want to use:

http-request redirect prefix https://www.test.com if !{ ssl_fc }

This will cause all redirects to target https://www.test.com regardless of the origin. But it will not solve the https://test.com to https://www.test.com issue as the condition (if !{ ssl_fc }) will not match.

You can probably use ACLs to add the required match, so something like this:

acl http     ssl_fc,not
acl host_www hdr_beg(host) www.
http-request redirect prefix https://www.test.com if http or !host_www