Ben Everard
Ben Everard

Reputation: 13804

Using .htaccess to force either HTTP or HTTPS

I have already have this code to force these URLs to HTTPS:

RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} ^/my/?.*$
RewriteCond %{REQUEST_URI} !^/my/basket/add?.*$
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} ^/login/?.*$
RewriteCond %{REQUEST_URI} ^/logout/?.*$
RewriteCond %{REQUEST_URI} ^/register/?.*$
RewriteCond %{REQUEST_URI} ^/newsletter/?.*$
RewriteCond %{REQUEST_URI} ^/reset-password/?.*$
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

And this works really well, but what I want to do is force any URL that does not comply with the above conditions to HTTP, firing a 301.

I don't want to create a list of HTTP pages and redirect them like I have with the HTTPS above. The secure pages URLs will always remain the same, unless I change the system somehow, but I can update them when needed. The non-secure pages can by dynamic, and created / edited by some of the sales team here, therefore these need to be target intelligently.

Any thoughts on how I could do this? It has to be done using .htaccess, I have been achieving this by handling it within our PHP framework, but this has caused a pretty significant performance problem as well as causing problems with our Google crawls.

Cheers!

Upvotes: 0

Views: 3903

Answers (2)

Alistair Evans
Alistair Evans

Reputation: 36473

A modification to the answer from Seidr, because in fact you only want to redirect if the HTTPS is on, when you want it to be off (also, there is no %{HTTP} variable). Again, put this after all your rules.

RewriteCond %{HTTPS} on
RewriteCond %{REQUEST_URI} !^/login/?.*$
RewriteCond %{REQUEST_URI} !^/logout/?.*$
RewriteCond %{REQUEST_URI} !^/register/?.*$
RewriteCond %{REQUEST_URI} !^/newsletter/?.*$
RewriteCond %{REQUEST_URI} !^/reset-password/?.*$
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Haven't tested this though, so not 100% that it will work.

Edit: Conditions for secure pages required, so that they will still be left in HTTPS mode.

Upvotes: 4

Seidr
Seidr

Reputation: 4936

As you are using the L flag on your rule there, you should be able to just use a RewriteCond such as the one below to rewrite any requests that have not been caught in the previous conditions to HTTP? Place it AFTER the rules you have posted. This seems a bit too obvious, but it might work.

RewriteCond %{REQUEST_URI} ^.*$
RewriteCond %{HTTP} OFF
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [L]

Upvotes: 1

Related Questions