[http] HAProxy redirecting http to https (ssl)

I'm using HAProxy for load balancing and only want my site to support https. Thus, I'd like to redirect all requests on port 80 to port 443.

How would I do this?

Edit: We'd like to redirect to the same url on https, preserving query params. Thus, http://foo.com/bar would redirect to https://foo.com/bar

This question is related to http redirect ssl https haproxy

The answer is


A slight variation of user2966600's solution...

To redirect all except a single URL (In case of multiple frontend/backend):

redirect scheme https if !{ hdr(Host) -i www.mydomain.com } !{ ssl_fc }

Can be done like this -

  frontend http-in
   bind *:80
   mode http
   redirect scheme https code 301

Any traffic hitting http will redirect to https


If you want to rewrite the url, you have to change your site virtualhost adding this lines:

### Enabling mod_rewrite
Options FollowSymLinks
RewriteEngine on

### Rewrite http:// => https://
RewriteCond %{SERVER_PORT} 80$
RewriteRule ^(.*)$ https://%{HTTP_HOST}$1 [R=301,NC,L]

But, if you want to redirect all your requests on the port 80 to the port 443 of the web servers behind the proxy, you can try this example conf on your haproxy.cfg:

##########
# Global #
##########
global
    maxconn 100
    spread-checks 50
    daemon
    nbproc 4

############
# Defaults #
############
defaults
    maxconn 100
    log global
    mode http
    option dontlognull
    retries 3
    contimeout 60000
    clitimeout 60000
    srvtimeout 60000

#####################
# Frontend: HTTP-IN #
#####################
frontend http-in
    bind *:80
    option logasap
    option httplog
    option httpclose
    log global
    default_backend sslwebserver

#########################
# Backend: SSLWEBSERVER #
#########################
backend sslwebserver
    option httplog
    option forwardfor
    option abortonclose
    log global
    balance roundrobin
    # Server List
    server sslws01 webserver01:443 check
    server sslws02 webserver02:443 check
    server sslws03 webserver03:443 check

I hope this help you


redirect statement is legacy

use http-request redirect instead

acl http      ssl_fc,not
http-request redirect scheme https if http

Why don't you use ACL's to distinguish traffic? on top of my head:

acl go_sslwebserver path bar
use_backend sslwebserver if go_sslwebserver

This goes on top of what Matthew Brown answered.

See the ha docs , search for things like hdr_dom and below to find more ACL options. There are plenty of choices.


I don't have enough reputation to comment on a previous answer, so I'm posting a new answer to complement Jay Taylor's answer. Basically his answer will do the redirect, an implicit redirect though, meaning it will issue a 302 (temporary redirect), but since the question informs that the entire website will be served as https, then the appropriate redirect should be a 301 (permanent redirect).

redirect scheme https code 301 if !{ ssl_fc }

It seems a small change, but the impact might be huge depending on the website, with a permanent redirect we are informing the browser that it should no longer look for the http version from the start (avoiding future redirects) - a time saver for https sites. It also helps with SEO, but not dividing the juice of your links.


frontend unsecured *:80
    mode http
    redirect location https://foo.bar.com

Like Jay Taylor said, HAProxy 1.5-dev has the redirect scheme configuration directive, which accomplishes exactly what you need.

However, if you are unable to use 1.5, and if you're up for compiling HAProxy from source, I backported the redirect scheme functionality so it works in 1.4. You can get the patch here: http://marc.info/?l=haproxy&m=138456233430692&w=2


I found this to be the biggest help:

Use HAProxy 1.5 or newer, and simply add the following line to the frontend config:

redirect scheme https code 301 if !{ ssl_fc }

The best guaranteed way to redirect everything http to https is:

frontend http-in
   bind *:80
   mode http
   redirect scheme https code 301

This is a little fancier using ‘code 301', but might as well let the client know it’s permanent. The ‘mode http’ part is not essential with default configuration, but can’t hurt. If you have mode tcp in defaults section (like I did), then it’s necessary.


To redirect all traffic:

redirect scheme https if !{ ssl_fc }

To redirect a single url (In case of multiple frontend/backend)

redirect scheme https if { hdr(Host) -i www.mydomain.com } !{ ssl_fc }


Add this into the HAProxy frontend config:

acl http      ssl_fc,not
http-request redirect scheme https if http

HAProxy - Redirecting HTTP Requests


In newer versions of HAProxy it is recommended to use

http-request redirect scheme https if !{ ssl_fc }

to redirect http traffic to https.


According to http://parsnips.net/haproxy-http-to-https-redirect/ it should be as easy as configuring your haproxy.cfg to contain the follow.

#---------------------------------------------------------------------
# Redirect to secured
#---------------------------------------------------------------------
frontend unsecured *:80
    redirect location https://foo.bar.com

#---------------------------------------------------------------------
# frontend secured
#---------------------------------------------------------------------
frontend  secured *:443
   mode  tcp
   default_backend      app

#---------------------------------------------------------------------
# round robin balancing between the various backends
#---------------------------------------------------------------------
backend app
    mode  tcp
    balance roundrobin
    server  app1 127.0.0.1:5001 check
    server  app2 127.0.0.1:5002 check
    server  app3 127.0.0.1:5003 check
    server  app4 127.0.0.1:5004 check

Simply:

frontend incoming_requsts
        bind *:80
        bind *:443 ssl crt *path_to_cert*.**pem**
        **http-request redirect scheme https unless { ssl_fc }**
        default_backend k8s_nodes

  acl host-example hdr(host) -i www.example.com

  # for everything not https
  http-request redirect scheme https code 301 unless { ssl_fc }

  # for anything matching acl
  http-request redirect scheme https code 301 if host-example !{ ssl_fc }

Examples related to http

Access blocked by CORS policy: Response to preflight request doesn't pass access control check Axios Delete request with body and headers? Read response headers from API response - Angular 5 + TypeScript Android 8: Cleartext HTTP traffic not permitted Angular 4 HttpClient Query Parameters Load json from local file with http.get() in angular 2 Angular 2: How to access an HTTP response body? What is HTTP "Host" header? Golang read request body Angular 2 - Checking for server errors from subscribe

Examples related to redirect

React-Router External link Laravel 5.4 redirection to custom url after login How to redirect to another page in node.js How to redirect to an external URL in Angular2? How to redirect to a route in laravel 5 by using href tag if I'm not using blade or any template? Use .htaccess to redirect HTTP to HTTPs How to redirect back to form with input - Laravel 5 Using $window or $location to Redirect in AngularJS yii2 redirect in controller action does not work? Python Requests library redirect new url

Examples related to ssl

Requests (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.") Error in PyCharm requesting website A fatal error occurred while creating a TLS client credential. The internal error state is 10013 curl: (35) error:1408F10B:SSL routines:ssl3_get_record:wrong version number How to install OpenSSL in windows 10? ssl.SSLError: tlsv1 alert protocol version Invalid self signed SSL cert - "Subject Alternative Name Missing" "SSL certificate verify failed" using pip to install packages ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749) Powershell Invoke-WebRequest Fails with SSL/TLS Secure Channel "ssl module in Python is not available" when installing package with pip3

Examples related to https

What's the net::ERR_HTTP2_PROTOCOL_ERROR about? Requests (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.") Error in PyCharm requesting website Android 8: Cleartext HTTP traffic not permitted ssl.SSLError: tlsv1 alert protocol version Invalid self signed SSL cert - "Subject Alternative Name Missing" How do I make a https post in Node Js without any third party module? Page loaded over HTTPS but requested an insecure XMLHttpRequest endpoint How to force Laravel Project to use HTTPS for all routes? Could not create SSL/TLS secure channel, despite setting ServerCertificateValidationCallback Use .htaccess to redirect HTTP to HTTPs

Examples related to haproxy

HAProxy redirecting http to https (ssl)