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.
Categories: Server Management, Tips & Tricks, Tutorials
Thanks, exactly what I was looking for!
apache?
How to redirect from www to non-www https?
Has anyone found a working solution in this environment?
Try the following to redirect www/www http to non-www https
#BEGIN force https from https://guides.wp-bullet.com
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteCond %{HTTP_HOST} ^(www\.)?example\[dot]com [NC]
RewriteRule ^(.*)$ https://example[dot]com/$1 [R=301,L]
#END force https
refer: https://guides.wp-bullet.com/single-hop-http-to-https-for-non-www-or-www-domain-with-htaccess/
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.
Thanks for sharing.
Our pleasure, glad to hear that you found it useful!
Hey, nice article on Redirect to HTTPS Using htaccess Behind Nginx Proxy with great information. salute for efforts. thanks.
Glad to hear you found the post useful, take care Niraj!