nginx detailed grammar rules

1、location [=|~|~*|^~] /uri/ { … }

location  = / {
  # Exact match / , no string after the hostname
  [ configuration A ] 
}
location  / {
  # Since all addresses start with /, this rule will match all requests
  # But regular and longest strings will be matched first
  [ configuration B ] 
}
location /documents/ {
  # Match any address starting with /documents/, after matching, continue to search down
  # Only when the following regular expression does not match, this one will use this one
  [ configuration C ] 
}
location ~ /documents/Abc {
  # Match any address starting with /documents/, after matching, continue to search down
  # Only when the following regular expression does not match, this one will use this one
  [ configuration CC ] 
}
location ^~ /images/ {
  # Match any address starting with /images/, after the match, stop searching for the regular, and use this one.
  [ configuration D ] 
}
location ~* \.(gif|jpg|jpeg)$ {
  # match all requests ending in gif,jpg or jpeg
  # However, all requests for images under /images/ will be processed by config D, because ^~ cannot reach this regex
  [ configuration E ] 
}
location /images/ {
  # The character matches /images/, and if you continue down, you will find that ^~ exists
  [ configuration F ] 
}
location /images/abc {
  # The longest character matches /images/abc, continue down, you will find ^~ exists
  # The order of placement of F and G is irrelevant
  [ configuration G ] 
}
location ~ /images/abc/ {
  # It is only valid if config D is removed: first match the address starting with config G for the longest time, continue to search down, and match this regular pattern, use
    [ configuration H ] 
}
location ~* /js/.*/\.js

2. Symbol explanation

=      starts with an exact match

The beginning of ^~      means that the url starts with a regular string, which is understood as matching the url path. nginx does not encode the url, so the request is /static/20%/aa, which can be matched by the rule ^$ /static/ /aa

~      case-sensitive regular matching

~*      case-insensitive regex match

!~ !~* Case-sensitive mismatch and case-insensitive mismatch

/       Universal match, any request will match


location = / {In the case of multiple location configurations, the matching order is first matching = second matching ^~ followed by regular matching according to the order in the file, and finally handing over to / general matching. When the matching is successful, the matching is stopped and the request is processed according to the current matching rules.

   #rule A
}
location = /login {
   #ruleB
}
location ^~ /static/ {
   #rule C
}
location ~ \.(gif|jpg|png|js|css)$ {
   #rule D
}
location ~* \.png$ {
   #rule E
}
location !~ \.xhtml$ {
   #rule F
}
location !~* \.xhtml$ {
   #rule G
}
location / {
   #ruleH
}

Then the effect is as follows:
access the root directory /, for example, http://localhost/ will match rule A and
access http://localhost/login will match rule B, and http://localhost/register will match rule H and
access http:/ /localhost/static/a.html will match rule C
to access http://localhost/a.gif, http://localhost/b.jpg will match rule D and rule E, but rule D takes precedence, rule E does not Function, and http://localhost/static/c.png is preferentially matched to rule C.
Access to http://localhost/a.PNG will match rule E, but will not match rule D, because rule E is not case-sensitive.
Visiting http://localhost/a.xhtml will not match rule F and rule G, and http://localhost/a.XHTML will not match rule G because it is not case sensitive. Rule F and rule G belong to the exclusion method, which matches the matching rule but will not match, so think about where it will be used in practical applications.
Visit http://localhost/category/id/1111 and finally match the rule H, because the above rules do not match, this time should be nginx forwarding the request to the back-end application server, such as FastCGI (php), tomcat (jsp), nginx exists as a reverse proxy server.

Therefore, in actual use, I personally think that there are at least three matching rules defined, as follows:
directly matching the website root, accessing the homepage of the website through the domain name is more frequent, using this will speed up the processing, the official website says.
This is directly forwarded to the back-end application server, or it can be a static home page

The first mandatory rule
location = / {
proxy_pass http://tomcat:8080/index
}
The second mandatory rule is to process static file requests, which is the strength of nginx as an http server.
There are two configuration modes, directory matching or Suffix matching, choose one of them or use them together
location ^~ /static/ {
root /webroot/static/;
}
location ~* .(gif|jpg|jpeg|png|css|js|ico)$ {
root /webroot/ res/;
}
The third rule is a general rule, which is used to forward dynamic requests to the back-end application server.
Non-static file requests are dynamic requests by default.
After all, you can grasp the popularity of some current frameworks according to the actual situation, with .php, .jsp There are few cases of suffix
location / {
proxy_pass http://tomcat:8080/
}

3. Rerite syntax

The rewrite function is to use the global variables provided by nginx or the variables set by yourself, combined with regular expressions and flags to realize url rewriting and redirection. rewrite can only be placed in server{}, location{}, if{}, and can only work on strings after the domain name except the passed parameters, such as http://seanlook.com/a/we/index .php?id=1&u=str rewrites only for /a/we/index.php. Syntax rewrite regex replacement [flag];

If relative domain names or parameter strings work, you can use global variable matching, or you can use proxy_pass to reverse proxy.
It shows that the functions of rewrite and location are a bit similar, and they can both achieve jumps. The main difference is that rewrite changes the path to obtain resources within the same domain name, while location is a control access or reverse proxy for a type of path, which can proxy_pass to other machines. . In many cases, rewrite will also be written in the location, and their execution order is:
execute the rewrite command of the server block,
execute the location match
, execute the rewrite command in the selected location, and
if one of the URIs is rewritten, execute 1- 3. Until a real file is found; if the loop exceeds 10 times, a 500 Internal Server Error will be returned.

server {
listen 80;
server_name start.igrow.cn;
index index.html index.php;
root html;
if ($http_host !~ “^star\.igrow\.cn$" {
rewrite ^(.*) http://star.igrow.cn$1 redirect;
}
}

4, flag flag bit

last - basically use this Flag.
break – abort Rewirte, no longer match
redirect – return HTTP status 302 for temporary redirect
permanent – ​​return HTTP status 301 for permanent redirect

Because 301 and 302 cannot simply return the status code, there must also be a redirected URL, which is why the return instruction cannot return 301, 302. The difference between last and break here is a bit difficult to understand:
last is generally written in server and if, while break generally uses
last in location without terminating the rewritten url matching, that is, the new url will go through the matching process from the server again, and break The matching
break and last after terminating the rewrite can be organized to continue to execute the following rewrite instructions

5, if instruction and global variables

The syntax is if(condition){…}, which judges the given condition. If true, the rewrite directive inside the curly braces will be executed, and the if condition can be any of the following:

When the expression is just a variable, if the value is empty or any string starting with 0 will be treated as false
When directly comparing the variable and the content, use = or !=
~regular expression matching, ~* case-insensitive matching, !~ case-sensitive mismatch

1. The following expressions can be used to judge:
-f and !-f are used to judge whether a file exists
-d and !-d are used to judge whether a directory exists
-e and !-e are used to judge whether a file or directory exists
-x and !-x are used to determine whether the file is executable

2. The following are global variables that can be used as judgments

 

if ($http_user_agent ~ MSIE) {
    rewrite ^(.*)$ /msie/$1 break;
} //If UA contains "MSIE", rewrite request to /msid/ directory
if ($http_cookie ~* "id=([^;]+)(?:;|$)") {
    set $id $1;
 } //If the cookie matches the regular, set the variable $id equal to the regular reference part
if ($request_method = POST) {
    return 405;
} //If the submission method is POST, return status 405 (Method not allowed). return cannot return 301,302
if ($slow) {
    limit_rate 10k;
} //Speed ​​limit, $slow can be set by the set command
if (!-f $request_filename){
    break;
    proxy_pass  http://127.0.0.1; 
} // If the requested filename does not exist, reverse proxy to localhost. The break here is also to stop the rewrite check
if ($args ~ post=140){
    rewrite ^ http://example.com/ permanent;
} //If the 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) {
        return 404;
    } // anti-theft chain
}

例: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:D:\nginx/html
$request_filename:D:\nginx/html/test1/test2/test.php

6. Anti-theft chain

location ~* \.(gif|jpg|swf)$ {
valid_referers none blocked start.igrow.cn sta.igrow.cn;
if ($invalid_referer) {
rewrite ^/ http://$host/logo.png;
}
}

7. Set the expiration time according to the file type

location ~* \.(js|css|jpg|jpeg|gif|png|swf)$ {
if (-f $request_filename) {
expires 1h;
break;
}
}

8. Common variables

$args : #This variable is equal to the parameters in the request line, same as $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 directive for the current request.
$host : The request 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.
$status request status
$body_bytes_sent send bytes
$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 username that has been 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 method (eg 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.
$server_name : Server name.
$server_port : The port number where the request arrives at the server.
$request_uri : The original URI containing the request parameters, excluding the hostname, eg: "/foo/bar.php?arg=baz".
$uri : The current URI without request parameters, $uri does not contain the hostname, such as "/foo/bar.html".
$document_uri : Same as $uri.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325121506&siteId=291194637