Apache Rewrite implements URL 301 redirection and Domain Name Redirection

Source: Internet
Author: User

To use the rewrite module, you must first install or load the rewrite module. There are two ways 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.

Server-level (httpd. conf) There are two methods, one is in httpd. in conf, RewriteEngine on is directly used to enable the rewrite function. In addition, the RewriteEngine on is used to enable the rewrite function locally. The following is an example, you must use RewriteEngine on in each virtualhost to enable the rewrite function. Otherwise, rules in virtualhost without RewriteEngine on will not take effect.

For directory-based (. htaccess), note that the FollowSymLinks attribute of this directory must be opened and RewriteEngine on must be declared in. htaccess.

2. Example:

Example 1: The following are the rules defined in a VM. The feature is to redirect the client request's host prefix not www.jb51.net and 70.40.213.183 to the host prefix for http://www.jb51.net, to avoid having the same content of the web page with multiple pointed domain names, such as http://jb51.net.Copy codeThe Code is as follows: NameVirtualHost 70.40.213.183: 80
ServerAdmin slj@jb51.net
DocumentRoot "/web"
ServerName jb51.net

RewriteEngine on # enable the rewirte Function
RewriteCond % {HTTP_HOST }! ^ Www.jb51.net [NC] # declare that the prefix of the host requested by the Client is not www.jb51.net. [NC] indicates case-insensitive.
RewriteCond % {HTTP_HOST }! ^ 70.40.213.183 [NC] # declare that the prefix of the host requested by the Client is not 70.40.213.183. [NC] indicates case-insensitive.
RewriteCond % {HTTP_HOST }! ^ $ # Declare that the prefix of the host requested by the Client is not blank
RewriteRule ^ (. *) http://www.jb51.net/[L] # indicates that if the prefix in the host requested by the Client meets the preceding conditions, Jump directly to http://www.jb51.net/, then l]stands to stop the rewrite operation and do not apply it again. Here. * matching all URLs does not contain line breaks. The () bracket function is to mark all characters so that they can be used later. is to reference (. *) character.

Example 2: Jump to www.jb51.net when you enter the domain name of en.jb51.netCopy codeThe Code is as follows: RewriteEngine on
RewriteCond % {HTTP_HOST} ^ en.jb51.net [NC]
RewriteRule ^ (. *) http://www.jb51.net/[L]

Example 3. Recently, the SAICA software has changed its domain name. The new domain name is www.jb51.net. In this case, the original domain name ss.jb51.net, as well as the address of the Forum region URL continues to be valid without 404 not found, such as the original http://ss.jb51.net/bbs/tread-60.html, so that it continues to be valid under the new domain name, click it and forward it to http://bbs.jb51.net/tread-60.html, and its other web pages, such as the original http:/// www.jb51.net/purchase
The rewrite rules should be written as follows:Copy codeThe Code is as follows: RewriteEngine On
RewriteCond % {REQUEST_URI} ^/bbs/
RewriteRule ^ bbs/(. *) http://bbs.jb51.net/#1 [R = permanent, L]
RewriteCond % {REQUEST_URI }! ^/Bbs/
RewriteRule ^ (. *) http://www.jb51.net/#1 [R = permanent, L]

3. Overview of Apache mod_rewrite rule rewriting flagCopy codeCode: 1) R [= code] (force redirect) force external redirection
Force the replacement string to add http: // thishost [: thisport]/prefix to the external URL. If the code is not specified, the default 302 HTTP status code will be used.
2) F (force URL to be forbidden) disables the URL and returns a 403HTTP status code.
3) G (force URL to be gone) forces the URL to be GONE and returns the response HTTP status code.
4) P (force proxy) enforces proxy forwarding.
5) L (last rule) indicates that the current rule is the last rule. After the analysis is stopped, the rule is overwritten.
6) N (next round) re-runs the rewrite process from the first rule.
7) C (chained with next rule) is associated with the next rule

If the rule matches, it is processed normally and the flag is invalid. If the rule does not match, all associated rules are skipped.Copy codeCode: 8) T = MIME-type (force MIME type) force MIME type
9) NS (used only if no internal sub-request) is used only for non-internal subrequests
10) NC (no case) is case insensitive
11) QSA (query string append) append request string
12) NE (no URI escaping of output) does not escape special characters
Example: RewriteRule/foo/(. *)/bar? Arg = P1 % 3d $1 [R, NE] will be able to correctly convert/foo/zoo to/bar? Arg = P1 = zoo
13) pass through to next handler to the next Processing
For example:
RewriteRule ^/abc (. *)/def $1 [PT] # will be handed over to/def rules for processing
Alias/def/ghi
14) S = num (skip next rule (s) skipping num rules
15) E = VAR: VAL (set environment variable) set environment Variables

4. Apache rewrite example set

URL redirection

Example 1:
At the same time, the following two requirements are met:
1. Access http://www.zzz.com/xxx.php with http://www.zzz.com/xxx/
2. Access http://yyy.zzz.com with http://www.zzz.com/user.php? Username = yyyCopy codeThe Code is as follows: RewriteEngine On
RewriteCond % {HTTP_HOST} ^ www.zzz.com
RewriteCond % {REQUEST_URI }! ^ User. php $
RewriteCond % {REQUEST_URI}. php $
RewriteRule (. *). php $ http://www.zzz.com/4101/ [R]
RewriteCond % {HTTP_HOST }! ^ Www.zzz.com
RewriteRule ^ (. +) % {HTTP_HOST} [C]
RewriteRule ^ ([^.] +) .zzz.com http://www.zzz.com/user.php? Username = $1

Example 2:

/Type. php? Typeid = *->/type *. html
/Type. php? Typeid = * & page = *->/type * page *. htmlCopy codeThe Code is as follows: 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]

5. Use Apache URL Rewrite to configure a Multi-User Virtual Server

To implement this function, you must first enable wildcard domain name resolution on the DNS server (by yourself or by looking for a Domain Name Service Provider ). For example, I will resolve all *. kiya. us and * .jb51.net to my IP address 70.40.213.183.

Next, let's take a look at the setting of *. kiya. us virtual host in my Apache.Copy codeThe Code is as follows: ServerAdmin webmaster@kiya.us
DocumentRoot/home/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

# Adddefacharcharset GB2312

RewriteEngine on
RewriteCond % {HTTP_HOST} ^ [^.] +. kiya. (cn | us) $
RewriteRule ^ (. +) % {HTTP_HOST} $1 [C]
RewriteRule ^ ([^.] +). kiya. (cn | us) (. *) $/home/www. kiya. us/sylvan $3? Un = $1 & % {QUERY_STRING} [L]

In this section, I set the Document Root of * .jb51.net and *. kiya. us To/home/www. kiya. us.

Now, I have configured the URL Rewrite rule.Copy codeThe Code is as follows: RewriteEngine on # enable the URL Rewrite Function
RewriteCond % {HTTP_HOST} ^ [^.] +. kiya. (cn | us) $ # matching condition. If the host name in the URL entered by the user is similar to xxxx. kiya. us or xxxx.jb51.net
RewriteRule ^ (. +) % {HTTP_HOST} $1 [C] # pass the complete address entered by the user (except for parameters in GET mode) as a parameter to the next rule, [C] means that the Chain Concatenates 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 the certificate expression to parse the URL address entered by the user, and pass the username information in the host name as a parameter named un to/home/www/dev. kiya. scripts in the us directory, and follow the input parameters of the GET method entered by the user. And specify 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 the URL format is http: // xxxx, it is called an external jump. When external redirection is used, the URL address in the browser will be changed to a new address. When internal redirection is used, the address in the browser will not change, and it looks more like the actual second-level domain name virtual server.

After the configuration, restart the Apache server!
Update May 1, 2009

Someone asked a question when I got online today:

Rewrite anti-leech regular
Do not allow the websites www.im286.com www.chinaz.com to be leeched.

The answer in the Forum is:Copy codeThe Code is as follows: RewriteEngine 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

An article about http://lamp.linux.gov.cn/Apache/ApacheMenu/mod/mod_rewrite.html

Update May 24,200 9

1. Whether full escape is required. For example, change chinaz.com to chinaz \. com in RewriteCond % {HTTP_REFERER} chinaz.com [NC ].
The answer is: both are acceptable.

2. When I was working on YOURcaddy.com (that is, the deformation of PlanetCoachella I made last year), I was unable to switch normally on the GoDaddy host. Then I found the problem:
It is used on HostMonster and my own machine.
RewriteRule ^ business/([^ \.] +) $ biz/detail. php? Name = $1 [L]
To be rewritten. On the Godaddy host, the following is the case:
RewriteRule ^ business/([^ \.] +) $/biz/detail. php? Name = $1 [L]
The target file contains one more/
Now, I think it may be because no RewriteBase is specified. I will verify it again in another day.

3. Add two examples for judging the user agent instance and the automatic extension of phpand the automatic replacement of. html to. php extension:
1

RewriteEngine on
RewriteCond % {HTTP_USER_AGENT} ^ MSIE [NC, OR]
RewriteCond % {HTTP_USER_AGENT} ^ Opera [NC]
RewriteRule ^. *-[F, L] Here "-" indicates no replacement. Visitors with IE and Opera browsers will be banned from accessing the site.

2

RewriteEngine 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 directories to display images only
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond % {REQUEST_FILENAME }! ^. * \. (Gif | jpg | jpeg | png | swf) $
RewriteRule. * $-[F, L]
</IfModule>

Update Jun 10,200 9

Supplement: rewrite the specified file extension.

Rewrite a file with some extensions:
RewriteRule (. *. css $ |. *. js $) gzip. php? $1 [L]
To exclude some extensions:
RewriteRule! \. (Js | ico | gif | jpg | JPG | png | PNG | css | pdf | swf) $ index. php

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.