In Apache, the RewriteCond statement has been a difficult problem for me. I tried to understand it multiple times without structure, this time I finally figured out what it meant. RewriteCond is like the if statement in our program. it indicates that if one or more conditions are met, the RewriteRule statement next to RewriteCond is executed, this is the most primitive and basic RewriteCond function. to facilitate understanding, let's take a look at several examples.
The code is as follows:
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 purpose of the preceding statement is to use the FF browser to access the index. the php file will automatically allow you to access the index. m. php file. when you use some mobile terminals to access the file, you will be directed to the index. the actual access to the php file is index. l. if you use another browser to access php, you will be redirected to index. b. php. The preceding statement is equivalent to the following statement in the program.
(Take the PHP statement as an example ):
The code is as follows:
If ($ _ SERVER ['http _ USER_AGENT '] = 'mozilla/123 ')
{
// Jump to the access to index. m. php
}
Else if ($ _ SERVER ['http _ USER_AGENT '] = 'Lynx ')
{
// Jump to access index. L. php
}
Else
// Jump to access index. B. php
See Example 2:
RewriteCond % {HTTP_REFERER} (www.test.cn)
RewriteRule (. *) $ test. php
The purpose of the preceding statement is that if the host address of the previous page you access is www.test.cn, the access to test. php will be redirected no matter which page you are currently accessing.
See Example 3:
The code is as follows:
RewriteCond % {REMOTE_HOST} ^ host1. * [OR]
RewriteCond % {REMOTE_HOST} ^ host2. * [OR]
RewriteCond % {REMOTE_HOST} ^ host3 .*
RewriteRule (. *) $ test. php
The purpose of the preceding statement is to jump to test. php if your address is host1, host2, or host3. It can be seen from this that the default AND between the RewriteCond statements is, if you want OR, you need to write it clearly.
Below are some useful rewrite rules added to your favorites:
RewriteCond % {REQUEST_FILENAME }! -F // if the file exists, access the file directly without RewriteRule. (if the file does not exist or the file does not exist, rewrite the file)
RewriteCond % {REQUEST_FILENAME }! -D // # directly access the directory without RewriteRule if the directory exists
RewriteCond % {REQUEST_URI }! ^. *(/. Css | /. js | /. gif | /. png | /. jpg | /. jpeg) $ // # if files with these suffixes are used, they are directly accessed without Rewrite.