Reputation: 21
I know there is lots of topics regarding my question. I checked them all and tried them out but can't make it work. I need to rewrite http to https on some pages only. After visiting https pages the URL would go back to http. This is what I have so far:
# Rewrite Rules for domain.com
RewriteEngine On
RewriteBase /
#Rewrite www to domain.com
RewriteCond %{HTTP_HOST} ^www\.domain\.com [NC]
RewriteRule ^(.*)$ http://domain.com/$1 [L,R=301]
#Rewrite to https
RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} /secure.php
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L]
#traffic to http://, except secure.php
RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} /secure.php
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L]
When I skip the last set of rules (traffic to http://, except secure.php) the secure.php page loads as https and is encrypted. FINE. With the last set of rules (traffic to http://, except secure.php) the URL rewrites to https, turns blue (SSL) for a second and disappears (no SSL) but the URL is still https.
Any idea? Jacek
Upvotes: 2
Views: 9898
Reputation: 15778
There's a mistake with the 3rd set of rules. Here's the solution: with the 3rd set of rules: if the https is "on" then if the URL doesn't contain "/secure" then redirect to http.
# Rewrite Rules for domain.com
RewriteEngine On
RewriteBase /
#Rewrite www to domain.com
RewriteCond %{HTTP_HOST} ^www\.domain\.com [NC]
RewriteRule ^(.*)$ http://domain.com/$1 [L,R=301]
#Rewrite to https
RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} /secure.php
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L]
#traffic to http://, except secure.php
RewriteCond %{HTTPS} on
RewriteCond %{REQUEST_URI} !(/secure.php)
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [L]
Off topic advice: please look for Yahoo Slow an their very clever advices on website optimisation and you'll see why it's always better to have the "www" before. You'd better do the opposite for your #1 rewrite rule: if there's no "www", then add it.
Please try to use the RewriteLog
directive: it helps you to track down such problems:
# Trace:
# (!) file gets big quickly, remove in prod environments:
RewriteLog "/web/logs/mywebsite.rewrite.log"
RewriteLogLevel 9
RewriteEngine On
Tell me if it works.
Upvotes: 4