RewriteCond REQUEST_URI - ^ doesn't work as expected

前端 未结 2 451
闹比i
闹比i 2021-02-10 16:54

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

2条回答
  •  囚心锁ツ
    2021-02-10 17:54

    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.

提交回复
热议问题