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]


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.

Categories: Server Management, Tips & Tricks, Tutorials

Simplifying Server Management

RunCloud is a cloud server management tool that allows you to maintain full control of your server and host multiple WordPress, WooCommerce, Laravel, and PHP applications with fast and easy configuration.

Start Your Free Trial

5 days free trial no credit card required cancel anytime

8 thoughts on “Redirect to HTTPS Using htaccess Behind Nginx Proxy

  1. Hi,
    I am using native nginx. What is the configuration for http to https And non www to www redirect?
    And if I set config in sever block it gets deleted after rebuild..
    Please help.

Leave a Comment

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