Original: http://seanlook.com/2015/05/17/nginx-location-rewrite/
1. location regular Writing location =/{# Exact Match/, cannot take any strings after host name[Configuration A]} Location/{# Because all the addresses start with/, so this rule will match all requests# But the regular and longest strings will match first[Configuration B]} Location/documents/{# Match any address that starts with/documents/, match later, and continue searching down# Only the following regular expressions do not match until this one is used[Configuration C]} Location ~/DOCUMENTS/ABC {# Match any address that starts with/documents/, match later, and continue searching down# Only the following regular expressions do not match until this one is used[Configuration CC]} Location ^~/images/{# matches any address that begins with/images/, matches, stops searching for regular, and uses this one. [Configuration D]} Location ~* \. (Gif|jpg|jpeg) $ {# matches all requests ending with gif,jpg or JPEGHowever, all requests/images/images will be processed by Config D because ^~ cannot reach this regular[Configuration E]} Location/images/{# character matches to/images/, continue down, will find ^~ exists[Configuration F]} LOCATION/IMAGES/ABC {# The longest character matches to/IMAGES/ABC, continue down, will find ^~ exists# F is not related to the placement order of G[Configuration G]} Location ~/images/abc/{# only remove config D is valid: first the longest match the beginning of the Config G address, continue to search, matching to this rule, 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 practice, individuals feel 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 page# first Required ruleLocation =/{Proxy_pass http://tomcat:8080/index}# The second required rule is to handle a static file request, which is Nginx's strength as an HTTP server# There are two configuration modes, directory matching or suffix matching, either one or useLocation ^~/static/{root/webroot/static/;}location ~* \. (Gif|jpg|jpeg|png|css|js|ico) $ {root/webroot/res/;}#第三个规则就是通用规则, used to forward dynamic requests to backend application servers#非静态文件请求就默认是动态请求, according to the actual grasp#毕竟目前的一些框架的流行, with a. 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 the name of the drop passed argument, such as http://seanlook.com/a/we/index.php?id=1&u=str
only/a/we/index.php overrides. Grammarrewrite 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] flag, 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
: Returns 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 to if(condition){...}
judge a 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 comparing variables and content directly, use
=
or!=
~
Regular expression matching, case ~*
-insensitive match, !~
case-sensitive mismatch
-f
and !-f
used to determine if a file exists
-d
and !-d
used to determine if a directory exists
-e
and !-e
used to determine if a file or directory exists.
-x
and !-x
used to determine if a file is executable
For example:
if ($http _user_agent ~ MSIE) { Rewrite ^ (. *) $/msie/break ; }//If UA contains"MSIE", rewrite request to/msid/directoryif ($http _cookie ~* "id= ([^;] +)(?:;|$)") {set $id $ ; }//If the cookie matches the regular, set the variable$id equals the regular reference part if ($request _method = POST) { return 405; }//If the Submit method is post, the status is returned405 (Method not allowed). Return cannot return 301,302 if ($slow) { Limit_rate10k;}//Speed limit,$slow can be set via the SET commandif (! -F $request _filename) { Break ;Proxy_pass/HTTP127.0.0.1; }//If the requested file name does not exist, reverse proxy to localhost. Here'sBreak also stops rewrite checkif ($args ~ post=) { rewrite ^ http://example.com/permanent;} If the query string contains"post=140", permanent redirect 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 authenticated by the Auth Basic module.
$request_filename
: The file path of the current request, generated by a root or alias instruction with a 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
: The server address, which 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.
Cases: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
: Match numbers
^
: Matches the start of a string
$
: Description of matching string
{n}
: Repeats n times
{n,}
: Repeat N or more times
[c]
: Matches a single character C
[a-z]
: Matches any of a-Z lowercase letters
The ()
matching between the parentheses can be referenced later by, which represents the contents of the second in the $1
$2
previous ()
section. What's confusing in regular is \
escaping special characters.
2.4 Rewrite instanceshttp {# define image Log Formatlog_format imagelog ' [$time _local] ' $image _file ' $image _type ' $body _bytes_sent " $status; # turn on rewrite logrewrite_log on ; server {root/home/www;Location /{# rewrite rule informationerror_log logs/rewrite.log notice; # Note that there is a ' single quote ' to avoid {}rewrite ' ^/images/([a-z]{2})/([a-z0-9]{5})/(. *) \. ( Png|jpg|gif) $ '/data?file= $. $4; # Note that you cannot add the "last" argument to the above rule, otherwise the following set instruction will not executeset $image _file $ ; set $image _type $4; }Location/data {# Specify the log format for the picture to analyze the picture type and sizeaccess_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 URLtry_files/$arg _file/image404.html; }Location =/image404.html {# Picture does not exist return specific informationreturn 404 "image not found\n"; }} is shaped like
/images/ef/uh7b3/test.png
The request, rewritten to
/data?file=test.png
, and then match to
location /data
, look first
/data/images/test.png
The file does not exist, if there is a normal response, if it does not exist then rewrite tryfiles to the new image404 location and return the 404 status code directly.rewrite ^/images/(. *) _ (\d+) x (\d+) \. ( Png|jpg|gif) $/resizer/$. $4?width=$2&height=? Last ; the file request for the shape
/images/bla_500x400.jpg
, rewritten to the
/resizer/bla.jpg?width=500&height=400
address, and will continue to try to match the location.
Nginx Configuration Location Summary and rewrite rule notation