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.
1 2 3 |
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
1 2 3 |
if ($http_x_forwarded_proto = 'http'){ return 301 https://$host$request_uri; } |
For IIS edit web.config, add following to
1 2 3 4 5 6 7 8 9 10 11 |
<rewrite> <rules> <rule name="Rewrite HTTP to HTTPS" stopProcessing="true"> <match url="^(.*)$"/> <conditions logicalGrouping="MatchAny"> <add input="{HTTP_X_FORWARDED_PROTO}" pattern="^http$"/> </conditions> <action type="Redirect" url="https://{HTTP_HOST}/{R:1}"/> </rule> </rules> </rewrite> |