Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force SSL/HTTPS with mod_rewrite [duplicate]

The following solution works for both proxied and unproxied servers. So if you are using CloudFlare, AWS Elastic Load Balancing, Heroku, OpenShift or any other Cloud/PaaS solution and you are experiencing redirect loops with normal HTTPS redirects, give it a try.

RewriteEngine On

# If we receive a forwarded http request from a proxy...
RewriteCond %{HTTP:X-Forwarded-Proto} =http [OR]

# ...or just a plain old http request directly from the client
RewriteCond %{HTTP:X-Forwarded-Proto} =""
RewriteCond %{HTTPS} !=on

# Redirect to https version
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# Put the rest of your rewrite rules here

Put this rule before your current rules:

RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

I was looking for this solution as well. I added Gumbo's solutions and it worked great for me. But my original was different. My site/app rewrite redirects everything through index.php (for fany urls and ../application) except for files you request specifically. (like an image or other static files in the public root) Here's my original, which I found off the ZF site a long time ago.

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]

Here's with Gumbo's additional rules to force SSL on the whole site. So far works good for me.

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]


RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^.*$ https://mydomain.com/\0 [L,QSA,R=301]