First, create a new. htaccess file and write the following content in it:
Rewriteengine on # rewriteengine is the rewrite engine switch on is to turn off rewriterule ([0-9] {1,}) $ index. php? Id = $1
Rewriterule: rewriterule is a rewrite rule that supports regular expressions. The above ([0-9] {1,}) is composed of numbers, and $ is the end sign, the description ends with a number!
Now we can implement pseudo-static pages. Write down the rules below:
<Ifmodule mod_rewrite.c> rewriteengine onrewriterule ([a-za-z000000001, 00000000-(0-90000000000001, 00000000.html $ index. php? Action = $1 & id = $2 </ifmodule>
([A-za-z000000001, 00000000-(%0-9000000001, 00000000.html $ is the rule, index. php? Action = $1 & id = $2 is the format to be replaced. $1 indicates the matching value of the first parenthesis, $2 indicates the second, and so on !!
Let's write a PHP script for processing:
Index. php
<? Phpecho 'your action is :'. $ _ Get ['action']; echo '<br/>'; echo 'your ID is :'. $ _ Get ['id'];?>
Now, in the browser, enter:
Localhost/view-12.html
The output is:
Your action is: View
Your ID is: 12
================================ Gorgeous split line ==========================
13 mod_rewrite application examples
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 subdomain name will be captured in % 2 (internal atom, 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) $ your image Address [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
If your host does not provide the 404 page redirection service, we will create it ourselves.
Rewritecond % {request_filename }! -Frewritecond % {request_filename }! -Drewriterule .? /404.php [l]
Here,-F matches the existing file name and-D matches the existing path name. Before you perform 404 redirection, this Code determines whether your file name and path name exist. You can also add one on the 404 page? Url = $1 parameter:
Rewriterule ^ /? (. *) $/404.php? Url = $1 [l]
In this way, you can do other things on the 404 page, such as default confidence, sending an email reminder, adding a search, and so on.
6. Rename the Directory
If you want to rename the directory on the website, try this:
Rewriterule ^ /? Old_directory/([A-z/.] +) $ new_directory/$1 [R = 301, l]
In the rule, I added a "." (note that it does not represent all characters and there is an escape character before it) to match the suffix of the file.
7.convert the suffix of .html to. php.
Previously, when the .html file can continue to be accessed, update your website link.
Rewriterule ^ /? ([A-z/] +) \. html $ 1.php [l]
This is not a webpage redirection, so visitors are invisible. Change the flag to [R = 301, l] as a permanent redirection (visible).
8. Create a link without a file suffix
If you want to make the link to your PHP website more concise and easy to remember-or hide the file suffix, try this:
Rewriterule ^ /? ([A-Z] +) $ 1.php [l]
If the website contains PHP and HTML files, you can use rewritecond to first determine whether the file with the suffix exists and then replace it:
Rewritecond % {request_filename}. php-frewriterule ^ /? ([A-zA-Z0-9] +) $ 1.php [l] rewritecond returns request_filename=.html-frewriterule ^ /? ([A-zA-Z0-9] +) $ 20.1.html [l]
If the file is suffixed with. php, this rule will be executed.
9. Check the specific parameters in the query variable.
If there is a special parameter in the URL, you can use rewritecond to identify whether it exists:
<
Rewritecond % {QUERY_STRING }! Uniquekey = rewriterule ^ /? Script_that_requires_uniquekey \. php $ other_script.php [QSA, l]
The above rules will check whether the uniquekey parameter in {QUERY_STRING} exists. If the {request_uri} value is script_that_requires_uniquekey, it will be directed to the new URL.
10. Delete query Variables
The mod_rewrite module of Apache automatically identifies the query variables unless you have made the following changes:
A). assign a new query parameter (you can use [QSA, l] flag to save the original query variable)
B) Add "?" to the end of the file name. (Such as index. php ?). Symbol "?" It is not displayed in the address bar of the browser.
11. display the current URI in a new format
For example
If this is the running URL:/index. php? Id = NNNN. We would like to change it to/NNNN and display it in a new format. First, we
To update the search engine to a new format, You have to redirect the old URLs to the new format. However, we have to ensure that the previous index. php can still run. Am I confused?
To implement the above functions, the trick is to add a tag "marker" that the visitor cannot see in the query variable ". We only need to reset the link without the "marker" mark in the query variable.
And then replace the original link with the new format. Then, use the [QSA] flag to add a "marker" mark to the existing parameter. The following is an implementation method:
Rewritecond % {QUERY_STRING }! Markerrewritecond % {QUERY_STRING} id = ([-a-zA-Z0-9 _ +] +) rewriterule ^ /? Index \. php $ % 1? [R = 301, l] rewriterule ^ /? ([-A-zA-Z0-9 _ +] +) $ index. php? Marker & id = $1 [l]
Here, the original URL: http://www.example.com/index.php? Id = NNNN, which does not contain marker, so it is the first rule
Redirect permanently to http://www.example.com/nnnn. the second rule redirects http://www.example.com/nnnnto
Http://www.example.com/index.php? Marker & id = NNNN, and added marker and ID = NNNN
Finally, mod_rewrite starts the processing process.
The second match, marker is matched, so ignore the first rule, where there is a "." character that will appear in the http://www.example.com/index.php? In marker & id = NNNN, so the second rule will be ignored, so we can complete it.
Note that this solution requires some extensions of Apache, so you will encounter many obstacles if your website is placed on a shared host.
12. Enable Security Services
Apache can identify whether you have enabled the Security Service by referencing the {HTTPS} and {server_port} variables in two ways:
Rewritecond % {request_uri} ^ secure_page \. php $ rewritecond % {HTTPS }! Onrewriterule ^ /? (Secure_page \. php) $ https://www.example.com/#1 [R = 301, l]
The above rule tests whether the {request_uri} value is equal to our security Page code, and {HTTPS} is not equal to on. If both conditions are met, the request will be redirected to the Security Service URI. In addition, you can use {server_port} to perform the same test. 443 is a common security service port.
Rewritecond % {request_uri} ^ secure_page \. php $ rewritecond % {server_port }! ^ 443 $ rewriterule ^ /? (Secure_page \. php) $ https://www.example.com/#1 [R = 301, l]
13. Enforce security services on a specific page
When you encounter a security service domain name and a non-security service domain name under the root directory of the same server, you need to use rewritecond to determine whether the security service port is occupied, and only the following list of pages are required as security services:
Rewritecond % {server_port }! ^ 443 $ rewriterule ^ /? (Page1 | page2 | page3 | page4 | page5) $ https://www.example.com/?1=r=301,l]
<
The following describes how to return a page that is not set as a security service to port 80:
Rewritecond % {server_port} ^443 $ rewriterule! ^ /? (Page6 | page7 | page8 | page9) $ http://www.example.com % {request_uri} [R = 301, l] <
Overview of Apache mod_rewrite rule rewriting flag
- 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.
- 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 = Zed
- 13) Pt (pass through to next handler) is passed 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
URL redirection instance
Example 1: (jump to the back of B by accessing the front a) 1. http://www.zzz.com/xxx.php-> http://www.zzz.com/xxx/2.http://yyy.zzz.com-> http://www.zzz.com/user.php? Username = YYY function rewriteengine onrewritecond % {http_host} ^ www. Zzz. comrewritecond % {request_uri }! ^ User \. php $ rewritecond % {request_uri} \. php $ rewriterule (. *) \. php $ http://www.zzz.com/4241/ [R] rewritecond % {http_host }! ^ Www. Zzz. comrewriterule ^ (. +) % {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 *. htmlrewriterule ^/type(%0-9%%%%%.html $/type. php? Typeid = $1 [pt] rewriterule ^/type(%0-9%%%%%%page(%0-9%%%%%%.html $/type. php? Typeid = $1 & page = $2 [pt] Example 3: Hide the rewritecond % {request_filename} of the index. php file }! -Drewritecond % {request_filename }! -Frewriterule ^ (. *) $ index. one problem encountered in PHP/$1 [QSA, PT, l] at work is that the write redirect configuration does not take effect correctly, but it is accurate to the httpd. the configuration in the conf file takes effect, but in. the htaccess file does not take effect. You can always find loadmodule rewrite_module modules/mod_rewrite.so <directory/> options followsymlinks AllowOverride all order deny, allow deny from all </directory> is also enabled, but no matter how the configuration is disabled, refer to the official manual to find :. conditions required for htaccess configuration: first, enable mod_rewrite: loadmodule rewrite_module modules/mod_rewrite.so <directory/> options followsymlinks AllowOverride all order deny, step 2 of allow deny from all </directory> needs to be introduced. htaccess (Change AllowOverride none to AllowOverride all. <directory "/usr/local/Apache/htdocs"> # possible values for the options directive are "NONE", "all", # or any combination: # indexes includes followsymlinks symlinksifownermatch execcgi Multiviews # note that "Multiviews" must be named * explicitly *-"options all" # doesn't give it to you. # The options directive is both complicated and important. please see # http://httpd.apache.org/docs/2.2/mod/core.html#options # for more information. # options-indexes followsymlinks provided des # AllowOverride controls what direves ves may be placed in. htaccess files. # It can be "all", "none", or any combination of the keywords: # options fileinfo authconfig limit # AllowOverride none ## controls who can get stuff from this server. # order allow, deny allow from all </directory>