Nginx Configuration Location Summary and rewrite rule notation

Source: Internet
Author: User
Article reprinted from: "Nginx configuration location Summary and rewrite rule writing"

1. Location regular notation

An example:

Location =/{# exact match/, no string after hostname [configuration A]}location/{# Because all addresses start with/, so this rule will match all requests # but regular and maximum characters String will first match [configuration B]}location/documents/{# Matches any address that begins with/documents/, matches later, and continues to search # only after the regular expression does not match, this article takes This [configuration C]}location ~/documents/abc {# matches any address that begins with/documents/, matches the match, and continues searching for # only the following regular expression does not match, this one will  Use this [configuration CC]}location ^~/images/{# Matches any address that begins with/images/, matches the match, and then stops searching for regular, using this. [Configuration D]} Location ~* \. (Gif|jpg|jpeg) $ {# matches all requests ending with gif,jpg or JPEG # However, all requests under/images/will be processed by Config D because ^~ cannot reach this regular [configuration E] }location/images/{# character matches to/images/, continues down, will find ^~ exists [configuration F]}location/images/abc {# Longest character matches to/images/abc, Continue down, you will find that ^~ exists # F is not related to the placement order of G [Configuration G]}location ~/images/abc/{# only remove config D is valid: first longest match config G address , continue to search, match to this regular, using [configuration H]}location ~*/js/.*/\.js
Exact match with = start
If only the request at the end of the root directory is matched in A, no strings can be followed.
^~ begins with a URI that begins with a regular string, not a regular match
~ Starts with a case-sensitive regular match;
~* start indicates a case-insensitive regular match
/generic match, if there is no other match, any request will match to
Sequential no priority:
(location =) > (location full path) > (location ^~ path) > (Location ~,~* regular order) > (Location section start path) > (/)
The above matching results
According to the location above, the following sample matches are set up:
/-Config A
Exactly match exactly, even if/index.html doesn't match.
/downloads/download.html-config B
After matching B, there is no match down, using B
/images/1.gif, Configuration D
Match to F, match down to D, stop down
/images/abc/def-config D
Longest match to G, down match D, stop down
You can see that any/images/beginning with a match to D and stop, FG write here is meaningless, H is never round, here just to illustrate the match order
/documents/document.html-config C
Match to C, there is no match down, use C
/documents/1.jpg, Configuration E
Match to C, down to regular to E
/documents/abc.jpg-config CC
Longest match to C, down regular order to CC, not down to E
Practical Use recommendations
So in actual use, the individual feels that there are at least three matching rule definitions, as follows:

#直接匹配网站根, through the domain name to visit the site home more frequently, using this will speed up processing, the official website said. #这里是直接转发给后端应用服务器了, can also be a static home # first required rule location =/{    Proxy_pass http://tomcat:8080/index}# the second required rule is to handle a static file request, This is nginx as the strength of the HTTP server # There are two configuration modes, directory matching or suffix matching, either one or use location ^~/static/{    root/webroot/static/;} Location ~* \. (Gif|jpg|jpeg|png|css|js|ico) $ {    root/webroot/res/;} #第三个规则就是通用规则, used to forward a dynamic request to the backend Application Server # non-static file request is the default is dynamic request, own according to the actual grasp # after all, some of the current framework of popular, with the. php,.jsp suffix is rare. Location/{    Proxy_ Pass http://tomcat:8080/}
Http://tengine.taobao.org/book/chapter_02.html
Http://nginx.org/en/docs/http/ngx_http_rewrite_module.html
2. Rewrite rules
The rewrite function is to implement URL rewriting and redirection in conjunction with regular expressions and flag bits using nginx-provided global variables or variables that you set yourself. Rewrite can only be placed in server{},location{},if{}, and can only work on strings that are outside of the domain name, except for parameters that are passed, such as Http://seanlook.com/a/we/index.php?id=1&u =str rewrite only for/a/we/index.php. Syntax rewrite regex replacement [flag];
If the relative domain name or parameter string works, you can use global variable matching, or you can use the Proxy_pass reverse proxy.
show that rewrite and location function a bit like, can achieve jump, the main difference is that rewrite is within the same domain name to change the path to obtain resources, and location is a class of paths to do control access or reverse proxy, you can proxy_pass to other machines. In many cases rewrite will also be written in the location, and their order of execution is:
Execute the rewrite directive for the server block
Perform a location match
Executes the rewrite directive in the selected location
If one of the step URIs is overridden, the loop executes 1-3 until the actual file is found and the loop exceeds 10 times, returning a Internal Server error error.
2.1 Flag Flag bit
Last: Equivalent to Apache's [L] tag, indicating completion rewrite
Break: Stop executing the subsequent rewrite instruction set for the current virtual host
Redirect: Returns 302 temporary redirect, the address bar will show the address after the jump
Permanent: Return 301 Permanent Redirect, the address bar will show the address after the jump
Because 301 and 302 cannot simply return a status code, there must also be a redirected URL, which is why the return instruction cannot return 301,302. Here the last and break differences are a bit difficult to understand:
Last is generally written in server and if, and break is generally used in location
Last does not terminate the rewritten URL match, that is, the new URL will go through the matching process again from the server, and break terminates the rewritten match
Both break and last can organize the continuation of the subsequent rewrite instructions.
2.2 If directives and global variables
If judgment instruction
The syntax is the IF (condition) {...}, judging the given condition condition. If true, the rewrite instruction within the curly braces will be executed, and the If condition (conditon) can be anything like:
When an expression is just a variable, if the value is empty or any string starting with 0 is treated as false
When you directly compare variables and content, use = or! =
~ Regular expression Match, ~* case-insensitive match,!~ case-sensitive mismatch
-F and!-f to determine if a file exists
-D and!-d to determine if a directory exists
-E and!-e to determine if a file or directory exists
-X and!-x to determine if a file is executable

For example:

if ($http _user_agent ~ MSIE) {    rewrite ^ (. *) $/msie/$1 break;}//If UA contains "MSIE", rewrite request to/msid/directory under if ($http _cookie ~* "Id= ([^;] +) (?:; |$) {    set $id $;}//If cookie matches regular, set variable $id equals regular reference part if ($request _method = POST) {    return 405;}//If the submission method is POS T, the state 405 (Method not allowed) is returned. Return cannot return 301,302if ($slow) {    limit_rate 10k;}//Speed limit, $slow can set the IF (!-f $request _filename) {Break by the set instruction    ;    Proxy_pass  http://127.0.0.1;}//If the requested file name does not exist, reverse proxy to localhost. The break here is also to stop rewrite check if ($args ~ post=140) {    rewrite ^ http://example.com/permanent;}//If query string contains "post=140 ", permanently redirected to Example.comlocation ~* \. (gif|jpg|png|swf|flv) $ {    Valid_referers none blocked www.jefflei.com www.leizhenfang.com;    if ($invalid _referer) {        return 404;    }//Anti-theft chain}
Global variables
The following is a global variable that can be used as an if judgment
$args: #这个变量等于请求行中的参数, with $query_string
$content _length: The Content-length field in the request header.
$content _type: The Content-type field in the request header.
$document _root: The value specified in the root instruction of the current request.
$host: Requests the Host header field, otherwise the server name.
$http _user_agent: Client Agent Information
$http _cookie: Client cookie Information
$limit _rate: This variable can limit the connection rate.
$request _method: The action requested by the client, usually get or post.
$remote _addr: The IP address of the client.
$remote _port: The port of the client.
$remote _user: The user name that has been validated by the Auth Basic module.
$request _filename: The file path of the current request, generated by the root or alias directive and the URI request.
$scheme: HTTP method (such as Http,https).
$server _protocol: The protocol used by the request, usually http/1.0 or http/1.1.
$server _addr: Server address, this value can be determined after a system call is completed.
$server _name: server name.
$server _port: The port number on which the request reached the server.
$request _uri: Contains the original URI of the request parameter and does not contain the hostname, such as "/foo/bar.php?arg=baz".
$uri: The current URI without the request parameter, $uri does not contain a hostname, such as "/foo/bar.html".
$document _uri: Same as $uri.
Example: http://localhost:88/test1/test2/test.php
$host: localhost
$server _port:88
$request _uri:http://localhost:88/test1/test2/test.php
$document _uri:/test1/test2/test.php
$document _root:/var/www/html
$request _filename:/var/www/html/test1/test2/test.php
2.3 Common Regular
. : matches any character except line break
? : Repeat 0 or 1 times
+: Repeat 1 or more times
*: Repeat 0 or more times
\d: Matching numbers
^: Match the start of a string
$: Description of matching string
{n}: repeat n times
{N,}: Repeat N or more times
[C]: match a single character C
[A-z]: matches any of a-Z lowercase letters
The matching between the parentheses () can be referred to later by A $, which represents the contents of the second (). What is confusing in regular is the escape of special characters.
2.4 Rewrite instances
Example 1:
HTTP {# Defines the image Log format Log_format imagelog ' [$time _local] ' $image _file ' $image _type ' $body _bytes_sent ' $stat    us     # Turn on rewrite log rewrite_log on;         server {root/home/www;                 Location/{# Rewrite rule information error_log logs/rewrite.log notice; Note Here to use ' single quotation marks ' to avoid {} rewrite ' ^/images/([a-z]{2})/([a-z0-9]{5})/(. *) \.                (png|jpg|gif) $ '/data?file=$3.$4;                # Note that you cannot add the "last" argument to the above rule, otherwise the following set instruction will not execute set $image _file $ $;        Set $image _type $4;                } location/data {# Specifies the log format for the picture to analyze the picture type and size Access_log logs/images.log mian;                Root/data/images; # Apply the variables defined earlier.        Judge the first file is not in, not to judge the directory is not in, if not yet jump to the last URL try_files/$arg _file/image404.html;        } location =/image404.html {# Picture does not exist returns specific information return 404 "image not found\n"; }}
The request to form such as/images/ef/uh7b3/test.png, rewrite to/data?file=test.png, so match to Location/data, first see/data/images/ The Test.png file does not exist, if it exists then the normal response, if not present, overrides the Tryfiles to the new image404 location, and returns the 404 status code directly.
Example 2:
Rewrite ^/images/(. *) _ (\d+) x (\d+) \. (png|jpg|gif) $/resizer/$1.$4?width=$2&height=$3? Last
A file request, such as/images/bla_500x400.jpg, is rewritten to the/resizer/bla.jpg?width=500&height=400 address and will continue to attempt to match the location.

The above describes the Nginx configuration location summary and rewrite rules, including the aspects of the content, I hope that the PHP tutorial interested in a friend helpful.

  • 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.