Redirect to HTTPS Using htaccess Behind Nginx Proxy

Sometimes when building your own web application from scratch, you might want to force your web application to redirect to HTTPS. You can achieve that with HSTS, but you are thinking it is better to add the redirection rules to the .htaccess too. So how to redirect to HTTPS using .htaccess behind Nginx Proxy?

The rewrite rules

RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{SERVER_NAME}/$1 [R,L]

Explanation

The first line is to tell Apache to enable rewrite engine. The second line is to tell Apache to run the third line if X-Forwarded-Proto is not https. And the third lines is to simply tell Apache to rewrite every HTTP request to HTTPS. The R and L flags are to tell Apache to rewrite the URL and stop rewrite if the URL is matched.

Why we are using %{HTTP:X-Forwarded-Proto} instead of %{HTTPS}? The Apache is behind Nginx and doesn’t know we are requesting our site using https protocol. Thus, Nginx will have to send X-Forwarded-Proto header for the backend to know about protocol we are using. X-Forwarded-Proto will only have two values, http or https.

Share This On
Share on facebook
Share on twitter
Share on linkedin
Share on reddit

6 thoughts on “Redirect to HTTPS Using htaccess Behind Nginx Proxy”

Leave a Comment

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

You May Also Like