I'm trying to accomplish 2 tasks with mod_rewrite:
If the URL, regardless of protocol, does not have the "www" subdomain, then add "www" to the URL.
If the URI begins with /secure.php AND the protocol is NOT https, then switch the protocol to https.
So I tried:
# Redirect to www subdomain
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
# Force SSL for secure.php URIs
RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} ^/secure.php
RewriteRule ^(.*)$ https://www.mysite.com%{REQUEST_URI} [R=301,L]
But I get a redirect loop when accessing /secure.php URIs. I can't figure out what the problem is, this is how I see the sequence of events:
- http://mysite.com/secure.php is requested
- The host name does not contain "www", so it passes the first condition
- The URL is updated to http://www.mysite.com/secure.php, and the process loops back to the top.
- The host name does contain "www", so it fails the first condition and skips the rewrite.
- HTTPS is off, so it matches the next condition, AND
- The URI begins with "/secure.php", so it matches both required conditions
- The URL is updated to https://www.mysite.com/secure.php, and the process loops back to the top.
- The host name does contain "www", so it fails the first condition, and skips the rewrite.
- HTTPS is not off, so it fails the next condition and skips the rewrite.
Have I got that right? What am I doing wrong here?
I also have one other rule in .htaccess for removing index.php from ExpressionEngine URLs:
RewriteCond $1 !\.(gif|jpe?g|png)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php/$1 [L]
So here's the entire .htaccess file:
RewriteEngine On
RewriteBase /
# Remove index.php from ExpressionEngine URIs
RewriteCond $1 !\.(gif|jpe?g|png)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php/$1 [L]
# Redirect to www subdomain
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
# Force SSL for /secure.php URIs
RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} ^/secure.php
RewriteRule ^(.*)$ https://www.mysite.com%{REQUEST_URI} [R=301,L]