I\'m building a site in codeigniter. I have a series of rewrite conditions & rules in the .htaccess file. The first set of rules turns SSL on or off depending on the first
Old question, I know, but there's another solution that might work better if you really want to stick with the %{REQUEST_URI}
condition:
RewriteCond %{HTTPS} !=on
RewriteCond %{REQUEST_URI} ^/?(admin|secure)$
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
The key difference versus the OP is the inclusion of /?
to check for the presence of a forward slash at the beginning of the URI. AFAIK, different Apache installations may or may not include the opening slash in %{REQUEST_URI}
.
One benefit of doing it this way is that you can apply the rule to multiple conditions:
RewriteCond %{HTTPS} !=on
RewriteCond %{REQUEST_URI} ^/?admin$ [OR]
RewriteCond %{REQUEST_URI} ^/?secure$ [OR]
RewriteCond %{REQUEST_URI} ^/?top-secret$
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
For the way I think, this is easier to work with than a long chain of pipe-delimited strings. This comes at the cost of a potential efficiency loss versus a single regex, but there are some other improvements you can make to offset this:
Use the lexographically equal operator !=on
. If you just use off
it gets treated as a regex.
Eliminate the RewriteRule pattern, replacing it with a single caret, then use the environment vars %{HTTP_HOST}
and %{REQUEST_URI}
. This saves the overhead of a longer regex pattern as well as the backrefs.