Apache Rewrite implements URL redirection and domain name redirection
The article is transferred from: http://www1.360quan.com/blog/show/4823429
Rewrite Function
The main function of Rewirte is to realize URL redirection, and its regular expressions are based on Perl language. It can be based on server level (httpd.conf) and directory level (.htaccess). If you want to use the rewrite module, you must first install or load the rewrite module. There are two methods, one is to install the rewrite module directly when compiling apache, the other is to install apache in DSO mode when compiling apache, and then use the source code and apxs to install the rewrite module.
Based on the server level (httpd.conf), there are two methods, one is to directly use RewriteEngine on to open the rewrite function under the global httpd.conf; the other is to use RewriteEngine on to open the rewrite function locally, the following will An example will be given. It should be noted that the rewrite function must be turned on with RewriteEngine on in each virtualhost. Otherwise, if there is no RewriteEngine on in the virtualhost, the rules in it will not take effect.
Based on directory level (.htaccess), one thing to note is that the FollowSymLinks property of this directory must be turned on and RewriteEngine on must be declared in .htaccess.
Examples
Example 1. The following are the rules defined in a virtual host. The function is to redirect the host prefix requested by the client not www.kiya.cn and 70.40.213.183 to the host prefix http://www.kiya.cn
, avoiding multiple domain names pointing to webpages with the same content, such as http://kiya.cn
.
NameVirtualHost 70.40.213.183:80
ServerAdmin slj@kiya.cn
DocumentRoot "/web"
ServerName kiya.cn
RewriteEngine on #Open the rewirte function
RewriteCond %{HTTP_HOST} !^www.kiya.cn [NC] #declare that the prefix in the host requested by Client is not www.kiya.cn, where [NC] means ignore case
RewriteCond %{HTTP_HOST} !^70.40.213.183 [NC] #declare that the prefix in the host requested by Client is not 70.40.213.183, where [NC] means ignore case
RewriteCond %{HTTP_HOST} !^$ #declare that the prefix in the host requested by Client is not empty
RewriteRule ^(.*) http://www.kiya.cn/ [L] #The meaning is that if the prefix in the host requested by the Client meets the above conditions, it will directly jump to 'http://www.kiya.cn /',[L] means stop the rewrite operation immediately and no other rewrite rules will be applied. The .* here means to match all URLs that do not contain newline characters. The function of the () brackets is to mark all the characters for later application. It is to quote the (.*) characters in the front.
Example 2. Jump to www.tsas.cn
when entering the domain name of en.tsas.cn
RewriteEngine on
RewriteCond %{HTTP_HOST} ^en.tsas.cn [NC]
RewriteRule ^(.*) <http://www.tsas.cn/> [L]
Example 3. Tsas Software has recently changed its domain name. The new domain name is www.tsas.cn
, which is shorter and easier to remember. At this time, it is necessary to direct the original domain name ss.kiya.cn
and the address of the forum ss.kiya.cn/bbs/
to the new domain name so that users can find it, and the original forum URL continues to be valid instead of 404 not found, such as the original http://ss.kiya.cn/bbs/tread-60.html
, let it continue to be valid under the new domain name, click and forward to http://bbs.tsas .cn/tread-60.html
, and other webpages, such as the original http://ss.kiya.cn/purchase
will not go to the second-level domain name bbs.tsas.cn/purchase
, but to www.tsas.cn/purchase
According to such requirements, the redirection rule should be written like this:
Rewrite Engine On
RewriteCond %{REQUEST_URI} ^/bbs/
RewriteRule ^bbs/(.*) http://bbs.tsas.cn/$1 [R=permanent,L]
RewriteCond %{REQUEST_URI} !^/bbs/
RewriteRule ^(.*) http://www.tsas.cn/$1 [R=permanent,L]
List of flags rewritten by Apache mod_rewrite rules
- R[=code](force redirect) force external redirection
Forcibly prefix the replacement string withhttp://thishost[:thisport]/
to redirect to an external URL. If code is not specified, the default 302 HTTP status code will be used. - F (force URL to be forbidden) disables the URL and returns a 403 HTTP status code.
- G(force URL to be gone) Force the URL to be GONE, return 410HTTP status code.
- P (force proxy) Forces the use of proxy forwarding.
- L(last rule) indicates that the current rule is the last rule, and the rewriting of the rule after the analysis is stopped.
- N(next round) reruns the rewriting process starting from the first rule.
- C(chained with next rule) is associated with the next rule
If the rule matches, it will be processed normally. If the flag is not matched, all the following associated rules will be skipped.
- T=MIME-type(force MIME type) Force MIME type
- NS (used only if no internal sub-request) is only used for not internal sub-requests
- NC(no case) case insensitive
- QSA(query string append) Append request string
- NE(no URI escaping of output) does not output escaping special characters
For example: RewriteRule /foo/(.*) /bar?arg=P1%3d$1 [R,NE] will correctly convert /foo/zoo to /bar?arg=P1=zoo - PT(pass through to next handler) Pass to the next processing
For example:
RewriteRule ^/abc(.*) /def$1 [PT] # will be handed over to the /def rule for processing
Alias /def /ghi - S=num(skip next rule(s)) skip num rules
- E=VAR:VAL(set environment variable) Set environment variable
Apache rewrite example collection
URL redirection
Example one:
Meet the following two requirements at the same time:
- Use
http://www.zzz.com/xxx.php
to visithttp://www.zzz.com/xxx/
- Use
http://yyy.zzz.com
to accesshttp://www.zzz.com/user.php?username=yyy
function
Rewrite Engine On
RewriteCond %{HTTP_HOST} ^www.zzz.com
RewriteCond %{REQUEST_URI} !^user.php$
RewriteCond %{REQUEST_URI}.php$
RewriteRule (.*).php$ http://www.zzz.com/$1/ [R]
RewriteCond %{HTTP_HOST} !^www.zzz.com
RewriteRule ^(.+) %{HTTP_HOST} [C]
RewriteRule ^([^.]+).zzz.com http://www.zzz.com/user.php?username=$1
Example two:
/type.php?typeid=*–> /type*.html
/type.php?typeid=*&page=* –> /type*page*.html
RewriteRule ^/type([0-9]+).html$ /type.php?typeid=$1 [PT]
RewriteRule ^/type([0-9]+)page([0-9]+).html$ /type.php?typeid=$1&page=$2 [PT]
Use Apache's URL Rewrite to configure a multi-user virtual server
To realize this function, you must first open the pan-domain name resolution of the domain name on the DNS server (do it yourself or find a domain name service provider to do it). For example, I resolve all .kiya.us and.kiya.cn to my IP address 70.40.213.183.
Then, take a look at the settings of the *.kiya.us virtual host in my Apache.
ServerAdmin webmaster@kiya.us
DocumentRoot /home/www/www.kiya.us
ServerName dns.kiya.us
ServerAlias dns.kiya.us kiya.us *.kiya.us
CustomLog /var/log/httpd/osa/access_log.log” common
ErrorLog /var/log/httpd/osa/error_log.log” AllowOverride None Order deny, allow #AddDefaultCharset GB2312
RewriteEngine on
RewriteCond %{HTTP_HOST} ^[^.]+.kiya.(cn|us)$
RewriteRule ^(.+) %{HTTP_HOST}$1 [C]
RewriteRule ^([^.]+).kiya.(cn|us)(.*)$ /home/www/www.kiya.us/sylvan$3?un=$1&%{QUERY_STRING} [L]
In this setting, I set the Document Root of .kiya.cn and.kiya.us to /home/www/www.kiya.us
Continue to read, here I have configured URL Rewrite rules.
the following sentence
RewriteRule ^(.+) %{HTTP_HOST}$1 [C] #Pass the complete address entered by the user (except GET parameters) as a parameter to the next rule, [C] means Chain to connect the next rule
RewriteRule ^([^.]+).kiya.(cn|us)(.*)$ /home/www/dev.kiya.us/sylvan$3?un=$1&%{QUERY_STRING} [L]
# The most important thing is this sentence, use regular expressions to parse the URL address entered by the user, and pass the user name information in the host name as a parameter named un to the script in the /home/www/dev.kiya.us directory , followed by the incoming parameters of the GET method input by the user. And indicate that this is the last rule ([L] rule).
# Note that the rewritten address specified in this sentence uses the absolute path on the server, which is an internal jump. If a URL format like http://xxxx is used, it is called an external redirect. If you use an external redirect, the URL address in the browsing browser will change to a new address, while using an internal redirect, the address in the browser will not change, which looks more like an actual second-level domain name virtual server.
After setting, restart the Apache server and you're done!
Update May 1, 2009
I came across a question on the Internet today:
Seeking Rewrite anti-leech rules
How to write the rules that www.im286.com and www.chinaz.com are not allowed to hotlink, and other websites are allowed to hotlink.
The answer in the forum is:
Rewrite Engine On
RewriteCond %{HTTP_REFERER} chinaz.com [NC]
RewriteCond %{HTTP_REFERER} im286.com [NC] RewriteRule .*.(jpg|jpeg|gif|png|rar|zip|txt|ace|torrent|gz|swf)$ http://www.xxx.com/fuck .png [R,NC,L]
Update May 7, 2009
Introduce an article:
http://lamp.linux.gov.cn/Apache/ApacheMenu/mod/mod_rewrite.html
Update May 24, 2009
1.Whether you need to use full escaping, for example, in
RewriteCond %{HTTP_REFERER} chinaz.com [NC]
Change chinaz.com
to chinaz.com
The answer is, both are possible.
2.Today, when I was working on YOURcaddy.com
(the transformation of PlanetCoachella I made last year), the GoDaddy host could not turn normally. Later, I found the problem:
On HostMonster as well as my own machine, the
RewriteRule ^business/([^.]+)$ biz/detail.php?name=$1 [L]
reached rewritten. And on the Godaddy host, it looks like this:
RewriteRule ^business/([^.]+)$ /biz/detail.php?name=$1 [L]
There is an extra / before the target file
Thinking about it now, it may be because RewriteBase is not specified. As for whether it is true, I will verify it another day.
3.Add two examples about judging USER AGENT and automatically adding .php extensions and automatically changing .html to .php extensions:
1
RewriteEngine on
RewriteCond %{HTTP_USER_AGENT} ^MSIE [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^Opera [NC]
RewriteRule ^.* – [F,L] #here "-" means no replacement, visitors whose browsers are IE and Opera will be prohibited from accessing.
2
Rewrite Engine On
RewriteBase /test
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ([^/]+)$ /test/$1.php #for example: /test/admin => /test/admin.php
RewriteRule ([^/]+).html$ /test/$1.php [L] #for example: /test/admin.html => /test/admin.php
Restrict the directory to only display images
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !^.*.(gif|jpg|jpeg|png|swf)$
RewriteRule .*$ – [F,L]
</IfModule>
Update Jun 10, 2009
Added, rewrites regarding specific file extensions.
Rewrite files with certain extensions:
RewriteRule (.*.css$|.*.js$) gzip.php?$1 [L]
If you want to exclude some extensions:
RewriteRule !.(js|ico|gif|jpg|JPG|png|PNG|css|pdf|swf)$ index.php