Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correctly switching between HTTP and HTTPS using .htaccess

Tags:

We've got a shopping site which we're hosting on a shared host (Mediatemple Gridserver). Some parts of the site need to use HTTPS (checkout etc) but the rest should be using HTTP.

Does anyone know how we can always force the correct use of HTTP/HTTPS for particular URLs? We've had it working in various states but we can't get a request for a page that should be on HTTP but is requested with HTTPS to switch back correctly.

I've had a look around SO but couldn't find a suitable answer to this.

like image 712
Alistair Holt Avatar asked Jul 10 '09 09:07

Alistair Holt


People also ask

How do I redirect my site using a .htaccess file?

Force the use of HTTPS instead of HTTP for your website If you want to force your website to use HTTPS, you need to use the RewriteEngine module in the . htaccess file. First of all, you need to turn on the RewriteEngine module in the . htaccess file and then specify the conditions you want to check.


2 Answers

I use something similar to this for my admin folder in wordpress:

#redirect all https traffic to http, unless it is pointed at /checkout RewriteCond %{HTTPS} on RewriteCond %{REQUEST_URI} !^/checkout/?.*$ RewriteRule ^(.*)$ http://mydomain.com/$1 [R=301,L] 

The RewriteCond %{HTTPS} on portion may not work for all web servers. My webhost requires RewriteCond %{HTTP:X-Forwarded-SSL} on, for instance.

If you want to force the reverse, try:

#redirect all http traffic to https, if it is pointed at /checkout RewriteCond %{HTTPS} off RewriteCond %{REQUEST_URI} ^/checkout/?.*$ RewriteRule ^(.*)$ https://mydomain.com/$1 [R=301,L] 

If you want some alternate ways to do it, check out askapache.

like image 138
Curtis Tasker Avatar answered Nov 12 '22 10:11

Curtis Tasker


This should work in pretty much every scenario and should work in your actual vhost or .htaccess:

RewriteEngine on RewriteCond %{SERVER_PORT} ^80$ RewriteRule ^(.*)$ https://%{SERVER_NAME}/%{REQUEST_URI} [R=301,L] 

(do not forget the slash before %{REQUEST_URI} as this may allow passing a portnumber, which is dangerous)

like image 27
Wil Moore III Avatar answered Nov 12 '22 12:11

Wil Moore III