The rewrite rules and examples of nginx

Source: Internet
Author: User

Through the rewrite rule can implement the specification URL, according to the variable to do the URL to turn and choose configuration, with good rewrite sometimes play a multiplier effect.

Grammar

Nginx rewrite compared to Apache better understand a lot, the main use of directives have if, rewrite, set, return, break, etc., where rewrite is the most critical instructions.

  1. Rewrite

    Syntax: rewrite regex replacement [flag];
    Default value:-
    Context: Server, location, if

    If the specified regular expression matches the URI, the URI is overwritten by the string defined by the replacement parameter. The rewrite directives are executed in the order in which they appear in the configuration file. Flag can terminate the execution of subsequent instructions. If the replacement string begins with "http:/" or "https://", nginx ends the execution process and returns a redirect to the client.
    The optional flag parameter can be one of them:
      • Last
        Stop executing the current round of the ngx_http_rewrite_module instruction set, and then find the new location that matches the changed URI;
      • Break
        Stop executing the current round of the ngx_http_rewrite_module instruction set;
      • redirect
        When the replacement string does not start with "http:/" or "https://", a temporary redirect with a return status code of 302 is used;
      • Permanent
        Returns a permanent redirect with a status code of 301.
    Example
    server {    ...    Rewrite ^ (/download/.*)/media/(. *) \. *$ $1/mp3/$2.mp3 last;    Rewrite ^ (/download/.*)/audio/(. *) \. *$ $1/mp3/$2.ra last  ;    return  403;    ...}
    However, when the above instructions are written in the "/download/" location, you should use the flag break instead of last, otherwise Nginx will repeat the 10-round loop, and then return the error of $ (break and last difference please refer to break):
    location/download/{    rewrite ^ (/download/.*)/media/(. *) \. *$ $1/mp3/$2.mp3 break;    Rewrite ^ (/download/.*)/audio/(. *) \. *$ $1/mp3/$2.ra break  ;    return  403;}
    If the replacement string includes a new request parameter, the previous request parameter is added to the new parameter. If you do not want this, add a question mark at the end of the replacement string "? ", it can be avoided, such as:
    Rewrite ^/users/(. *) $/show?user=$1? Last
    If the regular expression contains the character "}" or ";", the entire expression should be contained in a single quotation mark or double quotation mark reference.
  2. Break

    Syntax: break;
    Default value:-
    Context: Server, location, if

    stop processing the current round of the ngx_http_rewrite_module instruction set. such as:
    if ($slow) {Limit_rate 10k; break;} 
    , which must be marked with the last tag when using the alias directive. Use the break flag when using the PROXY_PASS directive. Last tag after the rewrite rule in this article has been executed, it will be in the server{...} The label re-initiates the request, and the break flag terminates the match after the rule match is complete, not the rule behind the match. Therefore, it is generally in the root location (that is, location/{...}) or write the rewrite rule directly in the Server tab, it is recommended to use the last tag, in a non-location (such as location/cms/{...}), then use the break flag.
    for Curly braces ({and}) , they can be used in a redirected regular expression, but also in the configuration file to split blocks of code, in order to avoid conflicts, If you have curly braces in regular expressions, enclose them in double quotation marks (or single quotes), such as: /photos/123456 Redirect to: /path/to/photos/12/1234/123456.png
    rewrite "/photos/([0-9]{2}) ([0-9]{2}) ([0-9]{2})"/path/to/photos/$1$2/$1$2$ 3.png> 
  3. if

    Syntax: if (condition) {...}
    Default:-
    Context: Server, location

    is used to check condition, and if true, executes rewrite module directives defined in braces. If directives do not support nesting, multiple conditions are not supported && and | | Processing.   The
    condition can be any of the following:
    • variable name, or False if the value of the variable is null or a string that starts with "0";
    • compares variables and strings using the "=" and "! =" operators;
    • using "~" (case sensitive) and "~*" (case-insensitive) operators match variables and regular expressions. A regular expression can contain a matching group, and subsequent occurrences of the matching result can be referenced using the variable $1..$9. If the regular expression contains the character "}" or ";", the entire expression should be contained in a single quotation mark or double quotation mark reference.
    • checks for the existence of the file using the "-F" and "!-f" operators, and
    • checks for the existence of the directory using the "-D" and "!-d" operators;
    • uses the "-E" and "!-e" operators to check for the existence of a file, directory, or symbolic link;
    • checks the executable file using the "-X" and "!-x" operators,
    such as:
    if ($http _user_agent ~ MSIE) {Rew Rite ^ (. *) $/msie/$1 break;} if ($http _cookie ~* "id= ([^;] +) (?:; |$) {set $id $;} if ($request _method = POST) {return 405;} if ($slow) {Limit_rate 10k;} if ($invalid _referer) {return 403;} 
  4. Set

    Syntax: Set variable value;
    Default value:-
    Context: Server, location, if

    Sets the value of the variable variable for the specified variable. Value can contain text, variables, or a combination of them, for example, reference below.
  5. Rewrite_log

    Syntax: Rewrite_log on | Off
    Default value:
    Rewrite_log off;
    Context: HTTP, server, location, if

    Turn on or off the processing log of the Ngx_http_rewrite_module module instruction to the notice level to the error log.
  6. Uninitialized_variable_warn

    Syntax: Uninitialized_variable_warn on | Off
    Default value:
    Uninitialized_variable_warn on;
    Context: HTTP, server, location, if

    Controls whether to log variables that are not initialized by warnings to the logs.
  7. Return

    Syntax: return code [text];
    return code URL;
    return URL;
    Default value:-
    Context: Server, location, if

    Stops processing and returns the specified code to the client. Status codes can use these values: 204, 400, 402-406, 408, 410, 411, 413, 416, and 500-504, and non-standard status code 444 ends the link in a way that does not send any header.

the global variables used by Nginx

$arg _parameter #这个变量包含GET请求中 If there is a value when the variable PARAMETER. $args #这个变量等于请求行中 (GET request) parameters, such as foo=123&bar=blahblah; $binary _remote_addr #二进制的客户地址. $body _bytes_sent #响应时送出的body字节数数量. Even if the connection is interrupted, the data is accurate. $content _length #请求头中的Content-length field. $content _type #请求头中的Content-type field. $cookie _cookie #cookie The value of the cookie variable $document_root #当前请求在root指令中指定的值. $document _uri #与 $uri the same. $host #请求主机头字段, otherwise the server name. $hostname #Set to the machine's hostname as returned by Gethostname$http_header$is_args #如果有 $args parameter, this variable equals "?", otherwise equals "", null value. $http _user_agent #客户端agent信息 $http _cookie #客户端cookie信息 $limit _rate #这个变量可以限制连接速率. $query _string #与 $args the same. $request _body_file #客户端请求主体信息的临时文件名. $request _method #客户端请求的动作, usually get or post. $remote _addr #客户端的IP地址. $remote _port #客户端的端口. $remote _user #已经经过Auth The user name validated by the Basic module. $request _completion #如果请求结束, set to OK. Empty when the request is not closed or if the request is not the last of the request chain string. $request _method #GET或POST $request _filename #当前请求的文件路径, generated by the root or alias instruction and URI request. $request _uri #包含请求参数的原始URI, does not include the hostname, such as "/foo/bar.php?arg=baz". Cannot be modified. $scheme #HTTP方法 (e.g. Http,https). $server _Protocol #请求使用的协议, usually http/1.0 or http/1.1. $server _addr #服务器地址, this value can be determined after a system call is completed. $server _name #服务器名称. $server _port #请求到达服务器的端口号. $uri #不带请求参数的当前URI, $uri does not include a hostname, such as "/foo/bar.html". This value may be inconsistent with $request_uri. $request _uri is the value that the browser sends over. The value is the value after rewrite. For example after doing the internal redirects.

Rewrite rule instances

    1. Redirect to a php file when the file and directory you are accessing does not exist
      if (!-e $request _filename) {rewrite ^/(. *) $ index.php last;}
    2. Catalogue Swap/123456/xxxx ====>/xxxx?id=123456
      Rewrite ^/(\d+)/(. +)/  /$2?id=$1 last;
    3. If the client is using IE browser, redirect to the/ie directory
      if ($http _user_agent  ~ MSIE) {Rewrite ^ (. *) $/ie/$1 break;}
    4. Disallow access to multiple directories
      Location ~ ^/(cron|templates)/{Deny all;break;}
    5. Prohibit access to files that begin with/data
      Location ~ ^/data {deny all;}
    6. Prohibit access to files with. Sh,.flv,.mp3 as the file suffix name
      Location ~. *\. (Sh|flv|mp3) $ {return 403;}
    7. Set the browser cache time for certain types of files
      Location ~. *\. (gif|jpg|jpeg|png|bmp|swf) $ {expires 30d;} Location ~. *\. (JS|CSS) $ {expires 1h;}

Comparison of rewrite rule examples between Nginx and Apache

  1. The general simple Nginx and Apache rules are not very different, basically can be fully compatible, for example:
    #ApacheRewriteRule  ^/abc/$   /web/abc.php [L] #Nginxrewrite  ^/abc/$  /web/abc.php last;
    We can see that as long as the Apache Rewriterule changed to Nginx Rewrite,apache [L] to last.
    If you change the Apache rule to Nginx and use the command nginx-t to check for errors, we can try to enclose the condition in quotation marks, for example:
    Rewrite "^/([0-9]{5}). html$"   /x.php?id=$1 last;
  2. The rewrite rules for Apache and Nginx have subtle differences in URL jumps:
    #ApacheRewriteRule ^/html/([a-za-z]+)/.*$  /$1/  [r=301,l] #Nginxrewrite ^/html/([a-za-z]+]/.*$/http//  $host/$1/premanent;
    We can see in the nginx jump, we need to add http://$host, which is strongly required in Nginx.
  3. Here are some of the corresponding relationships between Apache and Nginx rules
    Apache's rewritecond corresponds to Nginx if
    Apache's rewriterule corresponds to Nginx's rewrite
    Apache [R] corresponds to Nginx's redirect
    Apache's [P] corresponds to the last of Nginx
    Apache's [r,l] corresponds to Nginx's redirect
    Apache's [p,l] corresponds to Nginx's last
    Apache's [pt,l] corresponds to Nginx's last
    For example: Allow the designated domain name to access the site, the other domain names are turned to Www.xiaozhe.comApache:
    Rewritecond%{http_host}!^ (. *?) \.aaa\.com$ [Nc]rewritecond%{http_host}!^localhost$ rewritecond%{http_host}!^192\.168\.0\. (.*?) $RewriteRule ^/(. *) $ http://www.xiaozhe.com [r,l]
    Nginx:
    if ($host ~* ^ (. *) \.aaa\.com$) {set $allowHost ' 1 ';} if ($host ~* ^localhost) {set $allowHost ' 1 ';} if ($host ~* ^192\.168\.1\. *?) $) {Set $allowHost ' 1 ';} if ($allowHost!~ ' 1 ') {rewrite ^/(. *) $ http://www.xiaozhe.com redirect;}

The rewrite rules and examples of nginx

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.