A brief analysis of RewriteCond rule parameters in Apache

  • 2020-07-21 07:05:07
  • OfStack

RewriteCond is like if statement 1 in our program. It means to execute the RewriteRule statement next to RewriteCond if one or more conditions are met. This is the most primitive and basic function of RewriteCond.

RewriteEngine on
RewriteCond  %{HTTP_USER_AGENT}  ^Mozilla//5/.0.*
RewriteRule  index.php            index.m.php
RewriteCond  %{HTTP_USER_AGENT}  ^Lynx.*
RewriteRule  index.php            index.L.php 
RewriteRule  index.php            index.b.php

The role of the above statement is that when you are using FF browser to access index. php the file will automatically give you access to index. m. php this file, when you are using 1 some mobile terminal access, can let you to index. php this file access to the actual access is index L. php go, if you are using other browser access, can let you jump index. b. php. At image 1, the above statement is equivalent to the following statement in the program (for example, the PHP statement):

if($_SERVER['HTTP_USER_AGENT'] == 'Mozilla/5.0')
{
// Jump to the index.m.php Access to the 
}
else if($_SERVER['HTTP_USER_AGENT'] == 'Lynx')
{
// Jump to the index.L.php Access to the 
}
else
// Jump to the index.b.php Access to the 

Look at example 2:
RewriteCond %{HTTP_REFERER} (www.test.cn)
RewriteRule (.*)$ test.php
The above statement will redirect to www.test.cn if the last page you visited was hosted at www.test.cn.
Look at example 3:

RewriteCond %{REMOTE_HOST} ^host1.* [OR]
RewriteCond %{REMOTE_HOST} ^host2.* [OR]
RewriteCond %{REMOTE_HOST} ^host3.*
RewriteRule (.*)$ test.php

The above statement jumps to test.php if your address is host1 or host2 or host3. As you can see here, the default between RewriteCond statements is AND, and if you want OR, write it explicitly.
Here are 1 of my favorite useful rewriting rules:
RewriteCond % {REQUEST_FILENAME}! -ES53en // If the file exists, access the file directly without RewriteRule.(not the file or the file does not exist, overwrite it)
RewriteCond % {REQUEST_FILENAME}! -ES59en //# Access the directory directly without RewriteRule if the directory exists
RewriteCond % {REQUEST_URI}! ^.*(/.css |/.js |/.gif |/.png |/.jpeg)$//#

Related articles: