Location is a regular notation

An example:

Location = / {# exact match /, cannot be any string after the host name [configuration A]}

Location / {# Since all addresses start with a /, this rule will match all requests # but the re and longest string will match [configuration B]}

Location /documents/ {# match any address that starts with /documents/, then continue to search # If the regular expression does not match, this item will be used.

Location ~ /documents/Abc {# match any address that starts with /documents/. [configuration CC]}

Location ^~ /images/ {# matches any address that starts with /images/. [ configuration D ] }

The location ~ *. (GIF | JPG | jpeg) ${# matches all to GIF, JPG or jpeg # at the end of the request, however, all requests/images/pictures will be config D processing, [configuration E]}

Location /images/ {# character matches /images/, further down, ^~ exists [configuration F]}

Location /images/ ABC {# the longest character is matched to /images/ ABC, and further down, it is found that ^~ there is no relation between # F and G.

[configuration H] {/ /images/ ABC / {#}

location ~* /js/.*/.js

  • = indicates an exact match
  • For example, only the request at the end of the root directory is matched in A, and cannot be followed by any character string.
  • The beginning of ^~ indicates that the URI begins with a regular string, not a regular match
  • The beginning of ~ indicates case-sensitive regular matching.
  • The beginning of ~* indicates case-insensitive regular matching
  • / universal match, if there is no other match, any request will be matched

Order no priority: (location =) > (location ^~ path) > (location ~,~* regular order) > (location partial start path) > (/)

The above matching result is written in accordance with the above location. The following matching example is valid:

/ -> config A /downloads/download. HTML -> config B /downloads/download. HTML -> config B GIF -> configuration D to F, down to D, stop down /images/ ABC /def -> config D to G, down to D, Down you can see that anything that starts with /images/ will match D and stop. FG doesn’t make any sense here, H is never round, just to show the matching order /documents/document.html -> config C matches C, JPG -> configuration E matches to C, CC matches to E/Documents/abc.jpg -> config CC matches to C, CC matches to C Therefore, in practice, I think there are at least three definitions of matching rules, as follows: # Directly match the root of the website, using the domain name to visit the homepage of the website is more frequent, using this will speed up processing, according to the official website. Location = / {proxy_pass http://tomcat:8080/index}# the second mandatory rule is to handle static file requests. Location ^~ /static/ {root/ webroot/static/; root/ webroot/static/; } location ~* .(gif|jpg|jpeg|png|css|js|ico)$ { root /webroot/res/; }# the third rule is a generic rule for forwarding dynamic requests to back-end application servers. Belt. PHP, JSP suffix rarely location /} {proxy_pass http://tomcat:8080/ http://tengine.taobao.org/book/chapter02.html http://nginx.org/en/docs/http/ngxhttprewritemodule.html

Rewrite rules Rewrite is the Rewrite function, which uses nginx’s global or self-set variables in combination with regular expressions and flag bits to Rewrite urls and redirect them. Rewrite can only be written in server{},location{},if{}, and only on strings after domain names, excluding arguments passed. For example http://seanlook.com/a/we/index.php?id=1&u=str only on/a/we/index. The PHP to rewrite. Rewrite regex replacement [flag];

If relative domain names or parameter strings are in play, you can use global variable matching, or you can use proxy_pass reverse proxy.

Rewrite can change the path of a resource in the same domain, whereas location can do control access or reverse proxy for a type of path, and can proxy_pass to other machines. Rewrite will also be written in location in many cases, in this order:

The rewrite directive, which executes the server block, executes the location match, and executes the rewrite directive in the selected location. If one of the URIs is rewritten, repeat the loop 1-3 until the actual file is found. If this loop is repeated more than 10 times, 500 Internal Server Error is returned. Rewrite break: stop executing the rewrite directive set redirect: Permanent: The address bar will display the address after the redirect. 301 and 302 cannot simply return a status code, but must also have a redirected URL. This is why the return command cannot return 301,302. Here the difference between last and break is a little difficult to understand:

Last is written in server and if, while break is written in location

Last does not terminate the rewritten URL matching, that is, the new URL will go through the matching process from the server again. Rewrite (if){if(condition){if(condition){if(condition){if(condition){if(condition){if(condition){if(condition){if(condition){if(condition){if(condition){if(condition){if(condition){… }, judge the given condition. If true, the rewrite directive in braces will be executed, and the if condition (conditon) can be anything like the following:

When the expression is just a variable, use = or! If the value is empty or any string beginning with 0 will be treated as false when comparing the variable directly with the content. = ~ regular expression matching, ~* case insensitive matching,! ~ case sensitive mismatch -f and! -f determines whether the -d and! Files exist. -d is used to check whether directories -e and! Exist. -e is used to check whether files or directories exist. -x and! -x determines whether the file is executable. For example:

if ($http_user_agent ~ MSIE) { rewrite ^(.) $ /msie/$1break; // Rewrite ($http_cookie ~ “id=([^;])) rewrite ($http_cookie ~ “id=([^;])) (+)? :; |$)”) { set$id$1; If ($request_method = POST) {return405; } // If the submit Method is POST, the status 405 (Method not allowed) is returned. If ($slow) {limit_rate 10k; } // Speed limit, $slow can be set to if (! -f$request_filename){ break; Proxy_pass http://127.0.0.1; } // Reverse proxy to localhost if the requested filename does not exist. If ($args ~ post=140){rewrite ^ http://example.com/ permanent; } // If query String contains “post=140”, permanently redirect to example.com

location ~* .(gif|jpg|png|swf|flv)$ { valid_referers none blocked www.jefflei.com www.leizhenfang.com; if ($invalid_referer) { return404; Below are the global variables that can be used to determine if

$args: # This variable is equal to the argument in the request line, the same as $query_string $content_length: the content-Length field in the request header. $content_type: Content-Type field in the request header. $document_root: The value specified in the root directive in the current request. $host: request host header field, otherwise, 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: indicates the IP address of the client. $remote_port: client port. $remote_user: user name authenticated 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 (such as HTTP, HTTPS). $server_protocol: The protocol used for the request, usually HTTP/1.0 or HTTP/1.1. $server_ADDR: Server address, which can be determined after a system call. $server_name: indicates the server name. $server_port: port number for the request to reach the server. $request_URI: the original URI containing the request parameters, without the host name, e.g. “/foo/bar.php? Arg = baz “. $uri: the current URI with no request parameters. $URI does not contain a host name, such as “/foo/bar.html”. $document_URI: Same as $uri. Example: http://localhost:88/test1/test2/test.php $host: $serverport localhost: 88 $requesturi: http://localhost:88/test1/test2/test.php $documenturi: / test1 / test2 / test. The PHP $documentroot: $request_filename: / var/WWW/HTML/var/WWW/HTML/test1 / test2 / test. The regular commonly used PHP

. : Matches any character except newline? : Repeat 0 or 1 times

  • : Repeat 1 or more times
  • : repeat 0 or more times \ D: match digit ^ : match the beginning of string $: Introduction to match string {n} : repeat n times {n,} : repeat n times or more [c] : match single character c [a-z] : Matches between any of the parentheses () of the a-z lowercase letters can be referenced later by $1, which represents the contents of the second () above. A confusing part of the re is escaping special characters. Rewrite example 1:

Log_format imagelog ‘[$time_local] ‘$image_file’ ‘$image_type’ ‘$body_bytes_sent’ ‘$status; # enable rewrite_logon;


Copy the codeserver { root /home/www; Error_log logs/ rewrite-.log notice; # note here in 'single quotation marks, avoid {} rewrite' ^ / images/([a-z] {2})/([a - z0-9] {5})/(. *) \. (PNG | JPG | GIF) $'/data? file=$3.$4; Set $image_file$3; set$image_file$3; set$image_type$4; } location /data {# specify the log format for the image type and size access_log logs/images.log mian; root /data/images; # Apply the previously defined variables. Try_files /$arg_file /image404.html; try_files /$arg_file /image404.html; } location = /image404.html {# image404.html does not appear to return specific information return404"image not found\n"; }Copy the code

} to like/images/ef/uh7b3 / test. The PNG’s request, rewritten to/data? /data/images/test. PNG file exists, if it exists, it will respond properly. If it does not exist, rewrite tryfiles to image404 location. Returns a 404 status code.

Example 2:

rewrite ^/images/(.*)_(\d+)x(\d+).(png|jpg|gif)$ /resizer/$1.$4? width=$2&height=$3? last; For file requests like /images/bla_500x400.jpg, override to address /resizer/bla.jpg? Width =500&height=400 and continue trying to match location.