简体   繁体   中英

.htaccess scope of RewriteCond

I'm creating an .htaccess file for my need in my server:

<IfModule mod_rewrite.c>
   #Enable the Rewrite Engine
   RewriteEngine On

   #Rewrite the base to / if this is not local host
   RewriteBase /

   #Set the base in case of local development
   RewriteCond %{HTTP_HOST} ^(.*)localhost(.*)$
   RewriteBase /~asafnevo/api

   #Redirect every request to the index.php
   RewriteRule ^(.*)$ api/index.php?request=$1 [QSA,NC]

   # Prevent direct access to access to the index.php
   RewriteCond %{THE_REQUEST} index\.php
   RewriteRule ^(.*)index\.php$ - [F]


</IfModule>

I added the:

   #Set the base in case of local development
   RewriteCond %{HTTP_HOST} ^(.*)localhost(.*)$
   RewriteBase /~asafnevo/api

in order to have different base in my localhost development environment, but my question is when does the RewriteCond ends?

I tried to do

   RewriteBase /~asafnevo/api [L]

but I receive an 500 error.

Can someone please expend of scopes in matters of RewriteCond ?

A RewriteCond is only evaluated for the next RewriteRule directive that is encountered. Mod_rewrite will evaluate the first argument of RewriteRule first, then it will evaluate all RewriteCond it encountered after the last time it encountered a RewriteRule and if all evaluates to true, it will perform the requested rewrite.

Consider the following example:

RewriteCond . . #1
RewriteCond . . #2
RewriteRule . . #3

RewriteCond . . #4
RewriteRule . . #5

If the first argument of #3 matches, it will evaluate conditions #1 and #2, then rewrite to the second argument of #3. If the first argument of #5 matches, it will evaluate #4, then rewrite to the second argument of #5.

You are using RewriteBase incorrectly. You can't use the [L] flag because it's not a RewriteRule , hence the 500 error you are getting. Also you can only have 1 RewriteBase in your rules. If the file has multiple Bases, it will use the last one. So it will start to cause problems if you actually tried to use this in production with multiple RewriteBase 's.

The RewriteBase directive specifies the URL prefix to be used for per-directory (htaccess) RewriteRule directives that substitute a relative path.

http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewritebase

And RewriteCond is only used for Rules.

http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewritecond

You will just have to edit your .htaccess if you're on a local box or keep 2 copies and just rename it when you need it for locally.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM