Nginx Rewrite Rules

Source: Internet
Author: User
Tags vps domian
Recently, I tried to configure and install a website on VPs. VPs installed lnmp (Linux + nginx + MySQL + PHP) and often encountered some problems during rule resetting, directly using Apache rules to nginx does not work. In the past, Apache rewrite rules to nginx were not quite the same.

Here is just a simple record of some learning examples, the experts skipped, you can take a look.

Nginx rewrite rule-related commands
Commands related to nginx Rewrite Rules include if, rewrite, set, return, and break. Rewrite is the most critical command. A simple nginx rewrite rule syntax is as follows:

Rewrite ^/B/(. *) \. html/play. php? Video = $1 break;

If the if statement is added, the example is as follows:

If (! -F $ request_filename)

Rewrite ^/img/(. *) $/site/$ host/images/$1 last;

Comparison between nginx and Apache rewrite rule instances

Simple nginx and Apache rewrite rules are basically completely compatible. For example:

Apache rewrite rules:

Rewriterule ^/(mianshi | xianjing)/$/ZL/index. php? Name = $1 [l]

Rewriterule ^/Ceshi/$/ZL/Ceshi. php [l]

Rewriterule ^/(mianshi) _ ([A-Za-Z] +)/$/ZL/index. php? Name = $1 _ $2 [l]

Rewriterule ^/pingce ([0-9] *)/$/ZL/pingce. php? Id = $1 [l]

Nginx rewrite rules:

Rewrite ^/(mianshi | xianjing)/$/ZL/index. php? Name = $1 last;

Rewrite ^/Ceshi/$/ZL/Ceshi. php last;

Rewrite ^/(mianshi) _ ([A-Za-Z] +)/$/ZL/index. php? Name = $1 _ $2 last;

Rewrite ^/pingce ([0-9] *)/$/ZL/pingce. php? Id = $1 last;

The preceding example shows that the rewrite rule of Apache is changed to the rewrite rule of nginx, which is actually very simple: the rewriterule command of Apache is changed to the rewrite command of nginx, the [l] Mark of Apache is replaced with the last mark of nginx, And the content in the middle remains unchanged.

If Apache rewrite rules are changed to nginx Rewrite Rules, use the nginx-T command to check that the nginx. conf configuration file has a syntax error, you can try to add quotation marks to the conditions. For example, the nginx rewrite rule will report a syntax error:

Rewrite ^/(%0-9%%5%%%%.html $/X. jsp? Id = $1 last;

The quotation marks are correct:
Rewrite "^/(%0-9%%5%%%%.html $"/X. jsp? Id = $1 last;

The rewrite rules of Apache and nginx are slightly different in URL redirection:

Apache rewrite rules:
Rewriterule ^/html/tagindex/([A-Za-Z] +)/. * $/$1/[R = 301, l]

Nginx rewrite rules:
Rewrite ^/html/tagindex/([A-Za-Z] +)/. * $ http: // $ host/$1/permanent;

In the above example, we noticed that "http: // $ host" is added to the replacement string of the nginx rewrite rule, which is required in nginx.

In addition, the rewrite rules of Apache and nginx differ in variable names, for example:

Apache rewrite rules:
Rewriterule ^/user/login/$/user/login. php? Login = 1 & forward = http: // % {http_host} [l]

Nginx rewrite rules:
Rewrite ^/user/login/$/user/login. php? Login = 1 & forward = http: // $ host last;

Commands and tags with the same or similar functions of Apache and nginx rewrite rules are as follows:

Apache's rewritecond command corresponds to nginx's if command;
Apache's rewriterule command corresponds to nginx's rewrite command;
The [R] Mark of Apache corresponds to the Redirect mark of nginx;
The [p] Mark of Apache corresponds to the last mark of nginx;
The [R, l] Mark of Apache corresponds to the Redirect mark of nginx;
The [P, L] Mark of Apache corresponds to the last mark of nginx;
The [PT, l] Mark of Apache corresponds to the last mark of nginx;

Allow the specified domain name to access this site, other domain names will jump to the http://www.aaa.com

Apache rewrite rules:
Rewritecond % {http_host} ^ (.*?) \. Domain \. com $
Rewritecond % {http_host }! ^ Qita \. domain \. com $
Rewritecond % {document_root}/market/% 1/index.htm-F
Rewriterule ^/Wu/$/market/% 1/index.htm [l]

Nginx's if command does not support nesting, and does not support and, or, and other multi-condition matching. Compared with Apache's rewritecond, it is more troublesome. However, we can use the nginx configuration method on the next page to implement this example:

Nginx rewrite rules:
If ($ host ~ * ^ (.*?) \. Domain \. com $) set $ var_wupin_city $1;
Set $ var_wupin '1 ′;

If ($ host ~ * ^ Qita \. domain \. com $)

Set $ var_wupin '0 ′;

If (! -F $ document_root/market/$ var_wupin_city/index.htm)

Set $ var_wupin '0 ′;

If ($ var_wupin ~ '1 ′)

Rewrite ^/Wu/$/market/$ var_wupin_city/index.htm last;
}

 

Rewrite syntax

 

Syntax: Rewrite RegEx replacement flag

Default Value: None

Scope: Server, location, if

This directive changes URI in accordance with the regular expression and the replacement string. Directives are carried out in order of appearance in the configuration file.

This command modifies the URI or the string based on the expression. The command is executed according to the order in the configuration file.

Be aware that the rewrite RegEx only matches the relative path instead of the absolute URL. If you want to match the hostname, you should use an if condition, like so:

Note that the rewrite expression is only valid for relative paths. If you want to pair the host name, you should use the if statement.

Rewrite only changes the path and does not change the user's input parameters. Therefore, in the IF rule, you do not need to care about the parameters entered by the user in the browser. It will be automatically added after rewrite.,Therefore, we just add one? And a small parameter *** HTTPS = 1.

For nginx Rewrite Rules, refer:

  1. ~ Case-sensitive matching
  2. ~ * Case-insensitive match
  3. !~ And !~ * Case-insensitive and case-insensitive
  1. -F and! -F is used to determine whether a file exists.
  2. -D and! -D is used to determine whether a directory exists.
  3. -E and! -E is used to determine whether a file or directory exists.
  4. -X and! -X is used to determine whether a file is executable.
  1. Last is equivalent to the [l] Mark in Apache, indicating that rewrite is completed.
  2. The break terminates the match and does not match the subsequent rules.
  3. Redirect returns 302. the address bar of the temporary redirection will display the address after the jump.
  4. Permanent returns the 301 permanent redirect address bar, And the redirected address is displayed.
  1. $ ARGs
  2. $ Content_length
  3. $ Content_type
  4. $ Document_root
  5. $ Document_uri
  6. $ Host
  7. $ Http_user_agent
  8. $ Http_cookie
  9. $ Limit_rate
  10. $ Request_body_file
  11. $ Request_method
  12. $ Remote_addr
  13. $ Remote_port
  14. $ Remote_user
  15. $ Request_filename
  16. $ Request_uri
  17. $ QUERY_STRING
  18. $ Scheme
  19. $ Server_protocol
  20. $ Server_addr
  21. $ SERVER_NAME
  22. $ Server_port
  23. $ URI

Example of combining qeephp

  1. If (! -D $ request_filename ){
  2. Rewrite ^/([A-z-A-Z] +)/([A-z-A-Z] + )/? (. *) $/Index. php? Namespace = user & amp; Controller = $1 & amp; Action = $2 & amp; $3 last;
  3. Rewrite ^/([A-z-A-Z] + )/? $/Index. php? Namespace = user & amp; Controller = $1 last;
  4. Break;

Convert multiple directories to parameters
Abc.domian.com/sort/2 => abc.domian.com/index.php? Act = sort & name = ABC & id = 2

  1. If ($ host ~ * (. *) \. Domain \. com ){
  2. Set $ sub_name $1;
  3. Rewrite ^/sort \/(\ D + )\/? $/Index. php? Act = sort & cid = $ sub_name & id = $1 last;
  4. }

Directory swap
/123456/XXXX->/XXXX? Id = 123456

  1. Rewrite ^/(\ D +)/(. +) // $2? Id = $1 last;

For example, set nginx to redirect to the/nginx-ie directory when you use IE:

  1. If ($ http_user_agent ~ MSIE ){
  2. Rewrite ^ (. *) $/nginx-ie/$1 break;
  3. }

Automatically add "/" to the directory

  1. If (-d $ request_filename ){
  2. Rewrite ^/(. *) ([^/]) $ http: // $ host/$1 $2/permanent;
  3. }

Disable htaccess

  1. Location ~ /\. Ht {
  2. Deny all;
  3. }

Prohibit multiple directories

  1. Location ~ ^/(Cron | templates )/{
  2. Deny all;
  3. Break;
  4. }

Prohibit files starting with/Data
You can disable/data/multi-level directory. log.txt and other requests;

  1. Location ~ ^/Data {
  2. Deny all;
  3. }

Disable a single directory
Unable to stop. log.txt requests

  1. Location/searchword/cron /{
  2. Deny all;
  3. }

Prohibit a single file

  1. Location ~ /Data/SQL/data. SQL {
  2. Deny all;
  3. }

Set the expiration time for favicon.icoand robots.txt;
In this example, if favicon.icois set to 404 days, And robots.txt is set to 7 days, error logs are not recorded.

  1. Location ~ (Favicon. ico ){
  2. Log_not_found off;
  3. Expires 99d;
  4. Break;
  5. }
  6. Location ~ (Robots.txt ){
  7. Log_not_found off;
  8. Expires 7d;
  9. Break;
  10. }

Set the expiration time of a file. The value is 600 seconds and no access logs are recorded.

  1. Location ^ ~ /Html/scripts/loadhead_1.js {
  2. Access_log off;
  3. Root/opt/lampp/htdocs/web;
  4. Expires 600;
  5. Break;
  6. }

File anti-leeching and set expiration time
Here, return 412 is a custom HTTP status code. The default value is 403, which helps you find the correct request for leeching.
"Rewrite ^/http://leech.divmy.com/leech.gif?#display an anti-leech Image
"Access_log off;" does not record access logs, reducing pressure
"Expires 3D" browser cache for all files for 3 days

  1. Location ~ * ^. + \. (JPG | JPEG | GIF | PNG | SWF | RAR | zip | CSS | JS) $ {
  2. Valid_referers none blocked * .c1gstudio.com * .c1gstudio.net localhost 208.97.167.194;
  3. If ($ invalid_referer ){
  4. Rewrite ^/http://leech.divmy.com/leech.gif;
  5. Return 412;
  6. Break;
  7. }
  8. Access_log off;
  9. Root/opt/lampp/htdocs/web;
  10. Expires 3D;
  11. Break;
  12. }

Only use a fixed IP address to access the website and add a password.

  1. Root/opt/htdocs/WWW;
  2. Allow 208.97.167.194;
  3. Allow 222.33.1.2;
  4. Allow 231.152.49.4;
  5. Deny all;
  6. Auth_basic "c1g_admin ";
  7. Auth_basic_user_file htpasswd;

Convert files under multi-level directories into one file to improve Seo Performance
/Job-123-456-789.html to/job/123/456/789.html

  1. Rewrite ^/job-([0-9] +)-([0-9] +)-([0-9] + )\. HTML $/job/$1/$2/jobshow_#3.html last;

Point a folder in the root directory to a Level 2 Directory
Example/ShanghaiJob/point to/area/Shanghai/
If you change last to permanent, the address bar of the browser is/location/Shanghai/

  1. Rewrite ^/([0-9a-z] +) job/(. *) $/area/$1/$2 last;

The problem in the above example is that the access/Shanghai will not match

  1. Rewrite ^/([0-9a-z] +) Job $/area/$1/last;
  2. Rewrite ^/([0-9a-z] +) job/(. *) $/area/$1/$2 last;

In this way,/Shanghai can also be accessed, but the relative link on the page cannot be used,
For example, if the actual address of./list_1.html is/area/shanghia/list_1.html, it will become/list_1.html and cannot be accessed.

I cannot add automatic jump.
(-D $ request_filename) it has a condition that it must be a real directory, and my rewrite is not, so it has no effect

  1. If (-d $ request_filename ){
  2. Rewrite ^/(. *) ([^/]) $ http: // $ host/$1 $2/permanent;
  3. }

After knowing the reason, let me jump to it manually.

  1. Rewrite ^/([0-9a-z] +) Job $/$ 1job/permanent;
  2. Rewrite ^/([0-9a-z] +) job/(. *) $/area/$1/$2 last;

Redirection when the file and directory do not exist:

  1. If (! -E $ request_filename ){
  2. Proxy_pass http: // 127.0.0.1;
  3. }

Domain jump

  1. Server
  2. {
  3. Listen 80;
  4. SERVER_NAME jump.88dgw.com;
  5. Index index.html index.htm index. php;
  6. Root/opt/lampp/htdocs/WWW;
  7. Rewrite ^/http://www.88dgw.com /;
  8. Access_log off;
  9. }

Multi-domain redirection

  1. SERVER_NAME www.7oom.com/www.divmy.com /;
  2. Index index.html index.htm index. php;
  3. Root/opt/lampp/htdocs;
  4. If ($ host ~ "C1gstudio \. net "){
  5. Rewrite ^ (. *) http://www.7oom.com $1/permanent;
  6. }

Third-level domain jump

  1. If ($ http_host ~ * "^ (. *) \. I \. c1gstudio \. com $ "){
  2. Rewrite ^ (. *) http://top.88dgw.com $1 /;
  3. Break;
  4. }

Domain Name mirror

  1. Server
  2. {
  3. Listen 80;
  4. SERVER_NAME pai.c1gstudio.com;
  5. Index index.html index.htm index. php;
  6. Root/opt/lampp/htdocs/WWW;
  7. Rewrite ^/(. *) http://www.divmy.com/#1 last;
  8. Access_log off;
  9. }

A subdirectory for mirroring

  1. Location ^ ~ /Zhaopinhui {
  2. Rewrite ^. + http://zph.divmy.com/last;
  3. Break;
  4. }

Discuz ucenter home (uchome) rewrite

  1. Rewrite ^/(space | Network)-(. +) \. html $/$ 1.php? Rewrite = $2 last;
  2. Rewrite ^/(space | Network) \. html $/$ 1.php last;
  3. Rewrite ^/([0-9] +) $/space. php? Uid = $1 last;

Discuz 7 rewrite

  1. Rewrite ^ (. *)/archiver/(FID | tid)-[\ W \-] + \. html) $1/archiver/index. php? $2 last;
  2. Rewrite ^ (. *)/Forum-([0-9] +)-([0-9] +) \. html $1/Forumdisplay. php? FID = $2 & page = $3 last;
  3. Rewrite ^ (. *)/thread-([0-9] +)-([0-9] +)-([0-9] + )\. HTML $1/viewthread. PHP? Tid = $2 & extra = Page \ % 3d $4 & page = $3 last;
  4. Rewrite ^ (. *)/profile-(username | UID)-(. +) \. html $1/viewpro. php? $2 = $3 last;
  5. Rewrite ^ (. *)/space-(username | UID)-(. +) \. html $1/space. php? $2 = $3 last;
  6. Rewrite ^ (. *)/Tag-(. +) \. html $1/Tag. php? Name = $2 last;

Configure a domain name for a forum in discuz

  1. SERVER_NAME bbs.c1gstudio.com news.c1gstudio.com;
  2. Location = /{
  3. If ($ http_host ~ News \ .divmy.com $ ){
  4. Rewrite ^. + http://news.divmy.com/forum-831-1.html last;
  5. Break;
  6. }
  7. }

Optimization of discuz ucenter profile rewrite

  1. Location ^ ~ /Ucenter {
  2. Location ~ . * \. Php? $
  3. {
  4. # Fastcgi_pass Unix:/tmp/php-cgi.sock;
  5. Fastcgi_pass 127.0.0.1: 9000;
  6. Fastcgi_index index. php;
  7. Fcinclude gi. conf;
  8. }
  9. Location/ucenter/data/Avatar {
  10. Log_not_found off;
  11. Access_log off;
  12. Location ~ /(. *) _ Big \. jpg $ {
  13. Error_page 404/ucenter/images/noavatar_big.gif;
  14. }
  15. Location ~ /(. *) _ Middle \. jpg $ {
  16. Error_page 404/ucenter/images/noavatar_middle.gif;
  17. }
  18. Location ~ /(. *) _ Small \. jpg $ {
  19. Error_page 404/ucenter/images/noavatar_small.gif;
  20. }
  21. Expires 300;
  22. Break;
  23. }
  24. }

Jspace rewrite

  1. Location ~ . * \. Php? $
  2. {
  3. # Fastcgi_pass Unix:/tmp/php-cgi.sock;
  4. Fastcgi_pass 127.0.0.1: 9000;
  5. Fastcgi_index index. php;
  6. Fcinclude gi. conf;
  7. }
  8. Location ~ * ^/Index. php/
  9. {
  10. Rewrite ^/index. php/(. *)/index. php? $1 break;
  11. Fastcgi_pass 127.0.0.1: 9000;
  12. Fastcgi_index index. php;
  13. Fcinclude gi. conf;
  14. }

In addition, there is a tool that can directly convert Apache rules into nginx rules.

Http://www.anilcetin.com/convert-apache-htaccess-to-nginx/

Refer:

Http://wiki.nginx.org/NginxChsHttpRewriteModule

Http://blog.csdn.net/cnbird2008/archive/2009/08/04/4409620.aspx

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.