Redirect HTTP to HTTPS when using Reverse Proxy

When you are using Reverse Proxy like Nginx, Haproxy or Amazon ELB in front of web server and web server use HTTP to serve all traffic, you can use normal redirect code based HTTPS variable to do the redirect to HTTPS. You need to use X-Forwarded-Proto to do the redirect.

For Apache, add following code to .htaccess to Apache Virtual Host entry.

RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} =http
RewriteRule .* https://%{HTTP:Host}%{REQUEST_URI} [L,R=permanent]

For Nginx, add following to server entry for the domain name

if ($http_x_forwarded_proto = 'http'){
    return 301 https://$host$request_uri;
}

For IIS edit web.config, add following to section.


    
        
            
            
                
            
            
        
    

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *