sotirios9
sotirios9

Reputation: 167

Conditionally redirect pages from http to https or https to http

I am trying to edit my .htaccess file in order to have users go through an SSL connection for some pages, and not for others.

For example, when visiting a page called login.php (which sometimes is login.php?lo=true) they enter in their log in details. After they visit login.php they then proceed to check_login.php and if they are successful they move on to index.php.

My question is this: How do I change my .htaccess file in order for the following to occur:

My knowledge of ModRewrite rules is limited and so far I have implemented the following:

RewriteCond %{HTTPS} !=on
RewriteRule ^login\.php$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteRule ^login\.php?lo=true$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Any help would be greatly appreciated.

Upvotes: 3

Views: 147

Answers (2)

Salman Arshad
Salman Arshad

Reputation: 272106

There is no need to worry about query strings unless you use a ? in the replacement URL. Below are the two sets of rules you need (the second set of rules is simply the opposite of first):

RewriteCond %{HTTPS} !=on
RewriteRule  ^(?:login\.php|check_login\.php)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=302,L]

RewriteCond %{HTTPS} =on
RewriteRule !^(?:login\.php|check_login\.php)$  http://%{HTTP_HOST}%{REQUEST_URI} [R=302,L]

Note that I have used 302 redirects for testing. Do not forget to change to 301.

Upvotes: 3

Jon Lin
Jon Lin

Reputation: 143886

You can't put the query string in the regex in a rule, only the URI gets matched against, not the query string. Try:

RewriteCond %{HTTPS} off
RewriteRule ^login\.php$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteCond %{HTTPS} off
RewriteRule ^check_login\.php$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteCond %{HTTPS} on
RewriteCond %{REQUEST_URI} !^/?(check_)?login\.php
RewriteRule ^ http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Upvotes: 3

Related Questions