I have the following:
RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} protected [NC]
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [L,R=301]
RewriteCond %{HTTPS} on
RewriteCond %{REQUEST_URI} !protected [NC]
RewriteRule ^(.*)$ http://%{HTTP_HOST}/$1 [L,R=301]
If the directory is called "protected", make sure that the user is using https. If the directory is anything except "protected", make sure the user is using http.
This works great, but how do I specify additional directories?
Also, is there a way this can be accomplished without having to specify directories twice? One time for including it and one time for excluding it?
Thanks!
UPDATE
Although my "protected" folder was forced to use https due to my rules, any references to images, stylesheets, and javascripts that were not in the "protected" folder were still being redirected to http. This causes the "protected" page to only be partially secure. Adding the following prior to the redirect code solves this:
RewriteRule \.(css|gif|jpe?g|js|png|swf)$ - [L]
RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} protected [NC,OR]
RewriteCond %{REQUEST_URI} protected2 [NC,OR]
RewriteCond %{REQUEST_URI} protected3 [NC]
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [L,R=301]
RewriteCond %{HTTPS} on
RewriteCond %{REQUEST_URI} !protected [NC]
RewriteCond %{REQUEST_URI} !protected2 [NC]
RewriteCond %{REQUEST_URI} !protected3 [NC]
RewriteRule ^(.*)$ http://%{HTTP_HOST}/$1 [L,R=301]
you can use OR
to add more options!
Here is more detail on mod_rewrite conditions: http://httpd.apache.org/docs/current/mod/mod_rewrite.html#RewriteCond
I do it in the vhost configuration (LocationMatch
is not available in the htaccess, but that way you can make sure you never accidentally remove it):
(Note: replace __SERVER__
with your server, it is not automatic.)
<VirtualHost *:80>
...
<LocationMatch "(.*(p|P)hpMyAdmin.*)">
RedirectPermanent / https://__SERVER__/
</LocationMatch>
</VirtualHost>
<VirtualHost *:443>
...
<LocationMatch "!(.*(p|P)hpMyAdmin.*)">
RedirectPermanent / http://__SERVER__/
</LocationMatch>
</VirtualHost>
I have never tested the second scenario (redirect to non-secure) but it should work (not sure about the !
placement).
I have not yet found a good way to not specify them twice, but it is easy enough to copy the single line regex for the LocationMatch