URL rewriting rules

Source: Internet
Author: User

Enable mod_rewrite
Enable mod_rewrite module
To use the URL rewriting function, you must install the mod_rewrite module. Use the phpinfo () function to find the Apache Modules section. You can see the current apache loading module.
If mod_rewrite is not enabled, You need to configure the mod_rewrite.so path:
LoadModule rewrite_module modules/mod_rewrite.so
Apache2 has built-in mod_rewirte. In the VirtualHost configuration file, open the engine: RewriteEngine on.
Then you can use the rewrite syntax.
The Directory configuration of the VirtualHost file must be:

Options shortdes FollowSymLinks # symbolic links are allowed
AllowOverride All # Allow directory configuration file. htaccess. If AllowOverride None is not used

Using mod_rewrite to rewrite a URL mainly uses two basic commands: RewriteRule and RewriteCond.

RewriteRule command
RewriteRule Pattern Substitution [Flags]
Use regular expressions in Pattern and replacement to match the corresponding characters.
For example, the URL is as follows:
Http://www.example.com/display.php? Country = USA & state = California & city = San_Diego
The value of REQUEST_URI is "/country = USA & state = California & city = San_Diego". To display the city information of a country or state more friendly, it must be shown as follows:

Http://www.example.com/USA/California/San_Diego

The most common regular expression is (.*). It contains two elements: "point", indicating any character, and "Star", indicating all the previous characters. So (. *) will match all characters of {REQUEST_URI. The input string of the Rewrite engine is {REQUEST_URI}, that is, the domain name going out of the URL and "?" All query characters after the symbol.
In the redirected URL, "USA/California/San_Diego" is extracted. The regular expression in the matching mode is prototype:
(.*)/(.*)/(.*)
In the preceding regular expression, three values are stored in {REQUEST_URI} using two "/" segments. To solve our specific problem, we need to add some restrictions-after all, the first and last atoms can match any character.
Start, we can add some special characters, such as the regular "start" or "end", the "^" character indicates the start of the regular expression, and the "$" indicates the end of the regular expression.
^ (. *)/(. *)/(. *) $
{REQUEST_URI} starts. Apache will change the regular engine when changing the version. The first-generation Apache requires a slash, but the second-generation Apache does not! But we can use ^ /? (? Match the character itself or the first character) to be compatible with Apache. Coupled with the character matching restrictions, the final matching mode is:
^ /? ([A-zA-Z _] +)/([a-zA-Z _] +)/([a-zA-Z _] +) $
Complete representation:
RewriteEngine on
RewriteRule ^ /? ([A-zA-Z _] +)/([a-zA-Z _] +)/([a-zA-Z _] +) $ display. php? Country = $1 & state = $2 & city = $3 [L]
RewriteRule uses the matched content from $1 to $9 Reference Mode (), which is called reverse reference. For URL:

Http://www.example.com/USA/California/San_Diego

$1 = USA, $2 = California, $3 = San_Diego

RewriteRule Option
"Redirect | R [= code]" Force redirect. It is often referenced to trigger the visible orientation. By default, it is a temporary redirect of HTTP 302, but you can specify the specific HTTP Code. For example, you can use [R = 301] to indicate that this is a permanent redirect, this is quite useful for search engines to capture your redirected webpage.
"Proxy | P" is forced as a proxy
"Forbidden | F" 403 forbidden. Tells Apache not to provide a page when responding to a request. The principle is that Apache sends a 403 HTTP response, which can protect the website from unauthorized or other leeching access.
"Nocase | NC" ignores the case in the regular expression. It is often used on the {HTTP_HOST} server parameter because the domain name is case insensitive.
"Next | N" returns to the first rule. This allows you to rewrite conditional loop matching. It is useful when you do not know the number of characters in {REQUEST_URI.
"Last | L" is the last rule. It tells the Apache server that a series of conditions or rules will end after they appear. In other words, if [L] does not appear, mod_rewrite will continue to be executed.
"Noescape | NE" does not escape URIs in the output. This flag prevents mod_rewrite from applying regular URI escape rules to rewrite results. Generally, special characters (such as '%', '$', ';') are escaped as hexadecimal encoded values. This mark can prevent such escaping to allow symbols such as percent signs to appear in the output, for example:
RewriteRule/foo/(. *)/bar? Arg = P1 \ % 3d $1 [R, NE]
Can '/foo/zed' be redirected to a secure request'/bar? Arg = P1 = zed '.
"Skip | S = N" skips the following N rules.

RewriteCond command
RewriteCond TestString CondPattern [Flags]
The RewriteCond command defines a condition for a rule, that is, one or more RewriteCond commands before a RewriteRule command. The rewrite rule after the condition takes effect only when the current URI matches pattern and meets these conditions.
RewriteCond also has a reverse reference, but unlike the $ N Reference in RewriteRule, it uses % N reverse reference.
RewriteCond references Apache variable % {NAME_OF_VARIABLE}, for example, % {HTTP_HOST }.
In addition to using perl-style regular expressions, the condition pattern of RewriteCond has additional rules:
1. Use '! 'Character (Exclamation point) to reverse matching
2. ', =.
3. '-d' (a directory [directory]). Treat TestString as a path name and test whether it exists and is a directory.
4. '-f' (a regular file ). Consider TestString as a path name and test whether it exists and is a regular file.
5. '-S' (a non-empty regular file [size]). Consider TestString as a path name and test whether it exists. It is a regular file with a size greater than 0.
6. '-l' (a symbolic link [link]). Consider TestString as a path name and test whether it exists and is a symbolic connection.
7. '-f' (an existing file that is valid for the subrequest ). Test whether TestString is a valid file and can be accessed by all access control configured on the server. It uses an internal sub-Request for judgment. Please be careful when using it because it will reduce the server performance!

RewriteCond Option
'Nocase | NC '(no case ). It makes the test case insensitive. This flag only applies to the comparison of TestString and CondPattern, but does not take effect for the testing of the file system and sub-requests.
'Ornext | or' (OR next condition ). It combines conditions of several rules in the OR mode, instead of the default AND. A typical example is as follows:
RewriteCond % {REMOTE_HOST} ^ host1. * [OR]
RewriteCond % {REMOTE_HOST} ^ host2. * [OR]
RewriteCond % {REMOTE_HOST} ^ host3 .*
RewriteRule... Some special stuff for any of these hosts...
If this tag is not used, three conditions/rules must be used.

Server Variables
HTTP variable
HTTP_USER_AGENT, HTTP_REFERER, HTTP_COOKIE,
HTTP_FORWARDED, HTTP_HOST, HTTP_PROXY_CONNECTION, HTTP_ACCEPT
Connection and request Variables
REMOTE_ADDR, REMOTE_HOST, REMOTE_USER, REMOTE_IDENT,
REQUEST_METHOD, SCRIPT_FILENAME, PATH_INFO, QUERY_STRING, AUTH_TYPE
Internal Server Variables
DOCUMENT_ROOT, SERVER_ADMIN, SERVER_NAME, SERVER_ADDR,
SERVER_PORT, SERVER_PROTOCOL, SERVER_SOFTWARE
System Variables
TIME_YEAR, TIME_MON, TIME_DAY, TIME_HOUR,
TIME_MIN, TIME_SEC, TIME_WDAY, TIME
Mod_rewrite special value
API_VERSION, THE_REQUEST, REQUEST_URI, REQUEST_FILENAME

Example of URL rewriting
1. Add www tags to subdomain names
RewriteCond % {HTTP_HOST} ^ ([a-z.] + )? Example \. com $ [NC]
RewriteCond % {HTTP_HOST }! ^ Www \. [NC]
RewriteRule .? Http: // www.example.com % {REQUEST_URI} [R = 301, L]
This rule captures the % 1 variable of the second-level domain name. If it does not start with www, then www is added. The previous domain name and {REQUEST_URI} will follow it.

2. Remove the www mark from the domain name
RewriteCond % {HTTP_HOST }! ^ Example \. com $ [NC]
RewriteRule .? Http://example.com % {REQUEST_URI} [R = 301, L]

3. Remove the www tag, but save the sub-domain name
RewriteCond % {HTTP_HOST} ^ www \. ([a-z0-9 _] + \.)? Example \. com) $ [NC]
RewriteRule .? Http: // % 1% {REQUEST_URI} [R = 301, L]
Here, after matching the 1% variable, the sub-domain name will be captured in % 2 (internal atom), and what we need is this % 1 variable.

4. Prevent image leeching
Some webmasters steal your images on their websites by no means, consuming your bandwidth. You can add code to prevent such behavior.
RewriteCond % {HTTP_REFERER }! ^ $
RewriteCond % {HTTP_REFERER }! ^ Http: // (www \.)? Example \. com/[NC]
RewriteRule \. (gif | jpg | png) $-[F]
If the {HTTP_REFERER} value is not blank or is not from your own domain name, this rule uses [F] FLAG to block URLs ending with gif | jpg | png
If you despise this type of leeching, you can also change the image so that users who access the leeching website know that the website is stealing your images.
RewriteCond % {HTTP_REFERER }! ^ $
RewriteCond % {HTTP_REFERER }! ^ Http: // (www \.)? Example \. com/. * $ [NC]
RewriteRule \. (gif | jpg | png) $ http://www.example.com/hotlinked.gif [R = 301, L]
In addition to preventing image leeching links, the above rules replace all the images with the ones you set.
You can also prevent domain names from leeching your images:
RewriteCond % {HTTP_REFERER }! ^ Http: // (www \.)? Leech_site \. com/[NC]
RewriteRule \. (gif | jpg | png) $-[F, L]
This rule will block all image link requests on the domain name blacklist.
Of course, the above rules are based on the domain name obtained by {HTTP_REFERER}. If you want to change to an IP address, use {REMOTE_ADDR.

5. Redirect to 404 page if the file does not exist
RewriteCond % {DOCUMENT_ROOT} % {REQUEST_FILENAME }! -F
RewriteCond % {DOCUMENT_ROOT} % {REQUEST_FILENAME }! -D
RewriteRule .? /404.php [L]
-F matches the existing file name and-d matches the existing path name.

6. Create a link without a file suffix
RewriteCond % {REQUEST_FILENAME}. php-f
RewriteRule ^ /? ([A-zA-Z0-9] +) $ 1.php [L]
RewriteCond implements request_filename}.html-f
RewriteRule ^ /? ([A-zA-Z0-9] +) $ 20.1.html [L]
If the file is suffixed with. php, this rule will be executed.

7. Force HTTPS
RewriteCond % {HTTPS }! On
# RewriteCond % {SERVER_PORT }! ^ 443 $
RewriteCond % {HTTP_HOST} ^ ([a-z.] + )? Example \. com $ [NC]
RewriteRule ^ (. *) $ https: // % 1example.com $1 [R = 301, L]
To determine the HTTPS service, you can determine the Security Port (generally 443) or use the HTTPS variable. Use the https service forcibly for all URLs under the example.com domain name.
If you do not determine the domain name, you can do this:
RewriteCond % {HTTPS }! On
RewriteRule ^ /? (. *) $ Https: // % {SERVER_NAME}/$1 [R = 301, L]
Here, there is a slash/in front of $1. In fact, the reason for removing the slash in the matching mode is the same as the above effect.

Recommended Resources
Regular Expression tool firefox extension: Regular Expressions Tester
Regular Expression Table Introduction to the Tutorial:

Http://gnosis.cx/publish/programming/regular_expressions.html

Mod_rewrite in Apache:

Http://www.uplinux.com/download/doc/apache/ApacheManual/mod/mod_rewrite.html

URL rewriting guide for Apache documents:

Http://www.uplinux.com/download/doc/apache/ApacheManual/misc/rewriteguide.html

Learn Apache mod_rewrite: 13 Real-world Examples, original:

Http://www.sitepoint.com/article/apache-mod_rewrite-examples/

Learn Apache mod_rewrite: 13 Real-world Examples /? P = 357
A Beginner's Guide to URL Rewriting:

Http://www.sitepoint.com/article/guide-url-rewriting/

Apache Mod_rewrite example:

Http://dreamwaver.bokee.com/5692845.html

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.