nginx configuration location summary location regular and rewrite rules

  • 2020-05-15 03:36:34
  • OfStack

1. location regular writing

Let's start with an example:


location = / {
 #  An exact match  /  , the host name cannot be followed by any string 
 [ configuration A ]
}

location / {
 #  Because all the addresses are  /  So this rule will match all requests 
 #  But the regular and longest strings match first 
 [ configuration B ]
}

location /documents/ {
 #  Match any with  /documents/  The beginning of the address, match match, but also continue to search down 
 #  Only the following regular expression does not match when this happens 1 So this is what the bar is going to use 1 article 
 [ configuration C ]
}

location ~ /documents/Abc {
 #  Match any with  /documents/Abc  The beginning of the address, match match, but also continue to search down 
 #  Only the following regular expression does not match when this happens 1 So this is what the bar is going to use 1 article 
 [ configuration CC ]
}

location ^~ /images/ {
 #  Match any with  /images/  The beginning of the address, match match, stop searching down the regular, take this 1 The article. 
 [ configuration D ]
}

location ~* \.(gif|jpg|jpeg)$ {
 #  Match all with  gif,jpg or jpeg  Closing request 
 #  However, all requests  /images/  The picture below will be  config D  Deal with, because  ^~  I can't get here 1 A regular 
 [ configuration E ]
}

location /images/ {
 #  Character matching to  /images/ If you keep going, you'll see  ^~  There are 
 [ configuration F ]
}

location /images/abc {
 #  Longest character match to  /images/abc If you keep going, you'll see  ^~  There are 
 # F with G It doesn't matter what order you put it in 
 [ configuration G ]
}

location ~ /images/abc/ {
 #  Only remove the  config D  To be effective: longest match first  config G  The address at the beginning, I'm going to keep searching, and I'm going to go here 1 The regular bar is adopted 
  [ configuration H ]
}

location ~* /js/.*/\.js

location prefix

No prefix matches location that begins with the specified pattern

= exact match, not beginning with the specified pattern

~ regular matching, case sensitive

~* regular matching, case insensitive

^~ non-regular match, matches location starting with the specified pattern
General match, if there is no other match, any request will be matched

location matching order

Multiple regular location are matched directly in writing order and will not continue to match after success

Normal (non-regular) location will go down 1 until it finds the one with the highest match (maximum prefix match)

When the regular location and the regular location exist simultaneously, if the regular match is successful, the normal match will not be performed

When all types location exist, "=" matches > "^ ~" match > Regular match > Normal (maximum prefix matching)

Order:

(location =) > (location full path) > (location ^~ path) > (location ~,~* regular order) > (location partial start path) > (/)

The match above

Following the location notation above, the following matching example is valid:

/ -> config A

Exact exact match, even/index.html can't match

/downloads/download.html - > config B

After matching B, there is no match below and B is used

/images/1.gif - > configuration D

Match to F, match down to D, stop going down

/images/abc/def - > config D

Maximum match to G, go down to D, stop going down
You can see that anything that starts with /images/ is going to match to D and stop, FG doesn't make any sense here, H is never going to match, just to show the order

/documents/document.html - > config C

Match to C, no match below, C

/documents/1.jpg - > configuration E

Match to C, and go down to E

/documents/Abc.jpg - > config CC

Maximum match to C, down the regular order match to CC, not down to E

Practical recommendations

Therefore, in practice, I think there are at least 3 match rule definitions, as follows:


# Directly matching the website root, through the domain name to visit the website home page more frequently, using this will speed up the processing, the official website said. 
# This is directly forwarded to the back-end application server, or it could be 1 Static home page 
#  The first 1 Three mandatory rules 
location = / {
  proxy_pass http://tomcat:8080/index
}
#  The first 2 The required rule is to handle static file requests, which is nginx As a http Server strengths 
#  There are two configuration patterns, directory matching or suffix matching , Choose the 1 Or in combination 
location ^~ /static/ {
  root /webroot/static/;
}
location ~* \.(gif|jpg|jpeg|png|css|js|ico)$ {
  root /webroot/res/;
}
# The first 3 These rules are generic rules for forwarding dynamic requests to back-end application servers 
# Non-static file request is the default dynamic request, according to the actual grasp 
# After all, the current 1 Some frames are popular with tape .php,.jsp Suffixes are rare 
location / {
  proxy_pass http://tomcat:8080/
}

2. Rewrite rules

The function of rewrite is to rewrite and redirect url using the global variables provided by nginx or the variables set by nginx, in combination with regular expressions and flag bits. rewrite can only be placed in server{},location{},if{}, and can only work on strings following the domain name other than the passed parameters

For example http: / / ofstack com/a we/index php & # 63; id = 1 & u = str only to/a we/index php rewritten.

grammar rewrite regex replacement [flag];

You can use a global variable match or an proxy_pass reverse proxy if it works against a domain name or parameter string.

It shows that rewrite and location have similar functions, both of which can realize jump. The main difference is that rewrite is to change the access path of resources within the same domain name 1, while location is to control access or reverse proxy to the class 1 path, which can be proxy_pass to other machines.

In many cases, rewrite is also written in location. The order of execution is:

Execute the rewrite instruction for the server block

Perform location matching

Execute the rewrite instruction in the selected location

If one of these steps URI is overwritten, loop through 1-3 until the real file is found. If the loop exceeds 10 times, 500 Internal Server Error error is returned.

2.1 flag flag bit

[

last: the [L] flag equivalent to Apache, indicating completion of rewrite
break: stops executing the subsequent rewrite instruction set for the current virtual host
redirect: return 302 temporary redirection, 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

]

Since 301 and 302 cannot simply return status codes, they must also have redirected URL, which is why the return directive cannot return 301,302. The difference between last and break is a bit confusing here:

last1 is written in server and if, while break1 is used in location
last does not terminate the overwritten url match, that is, the new url will repeat the matching process from server once more, while break terminates the overwritten url match
Both break and last are able to organize the continuation of subsequent rewrite instructions

2.2 if instructions and global variables

if judgment instructions

Syntax for the if(condition){...} , to judge the given condition condition. If true, the rewrite instruction in curly braces will be executed, and the if condition (conditon) can be any of the following:

When the expression is just 1 variable, any string that starts with 0 is treated as false if the value is empty

Use when directly comparing variables and content = or !=

~ Regular expression matching, ~* Case-insensitive matching, !~ Case sensitive mismatch

-f and !-f To determine if a file exists

rewrite regex replacement [flag];0 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 the file is executable

Such as:


if ($http_user_agent ~ MSIE) {
  rewrite ^(.*)$ /msie/$1 break;
} // if UA contains "MSIE" . rewrite Request to the /msid/ directory 

if ($http_cookie ~* "id=([^;]+)(?:;|$)") {
  set $id $1;
 } // if cookie Match the regular, set the variable $id Is equal to the regular reference part 

if ($request_method = POST) {
  return 405;
} // If the submit method is POST , returns the status 405 ( Method not allowed ). return Can't return 301,302

if ($slow) {
  limit_rate 10k;
} // The speed limit, $slow Can be achieved by  set  Instruction set 

if (!-f $request_filename){
  break;
  proxy_pass http://127.0.0.1;
} // If the requested file name does not exist, reverse proxy to localhost  . Here, break Also stop rewrite check 

if ($args ~ post=140){
  rewrite ^ http://example.com/ permanent;
} // if query string Contained in the "post=140" , redirect permanently to example.com

location ~* \.(gif|jpg|png|swf|flv)$ {
  valid_referers none blocked www.jefflei.com www.leizhenfang.com;
  if ($invalid_referer) {
    return 404;
  } // Preventing hotlinking 
}

The global variable

The following are the global variables that can be used for if judgments

[

$args: # 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: the Content-Type field in the request header.
$document_root: the value currently requested in the root directive.
$host: request the host header field, otherwise the server name.
$http_user_agent: client agent information
$http_cookie: client cookie information
$limit_rate: this variable limits 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: client port.
$remote_user: username that has been authenticated by Auth Basic Module.
$request_filename: the file path for the current request, generated by the root or alias instructions and the URI request.
$scheme: the HTTP method (e.g. http, https).
$server_protocol: the protocol requested, usually HTTP/1.0 or HTTP/1.1.
$server_addr: server address, which can be determined after one system call.
$server_name: server name.
$server_port: the port number at which the request arrives at the server.
$request_uri: the original URI containing the request parameters, without the host name, such as "/foo/ bar.php ? arg = baz ".
$uri: current URI without request parameters, $uri without host name, 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 regularity

[

. : matches any character other than a newline
The & # 63; : repeat 0 or 1 times
+ : repeat 1 or more times
* : repeat 0 or more times
\d: matching Numbers
^ : matches the beginning of the string
$: an introduction to matching strings
{n} : repeat n times
{n,} : repeat n or more times
[c] : matches a single character c
[a-z] : matches any one of the lowercase letters of a-z

The match between the parentheses () can be referred to later by $1, and $2 represents the first (). The confusing thing inside the regular is that \ escapes special characters.

]

2.4 rewrite instance

Case 1:


http {
  #  define image Log format 
  log_format imagelog '[$time_local] ' $image_file ' ' $image_type ' ' $body_bytes_sent ' ' $status;
  #  Open rewrite log 
  rewrite_log on;

  server {
    root /home/www;

    location / {
        #  Rewrite rule information 
        error_log logs/rewrite.log notice;
        #  Notice the use of ' ' Avoid single quotes {}
        rewrite '^/images/([a-z]{2})/([a-z0-9]{5})/(.*)\.(png|jpg|gif)$' /data?file=$3.$4;
        #  Be careful not to add" last "Parameter, otherwise the following set Instruction will not be executed 
        set $image_file $3;
        set $image_type $4;
    }

    location /data {
        #  Specify the log format for the image to analyze the image type and size 
        access_log logs/images.log mian;
        root /data/images;
        #  Apply the previously defined variables. First determine whether the file is present, then determine whether the directory is present, if not, jump to the last 1 a url In the 
        try_files /$arg_file /image404.html;
    }
    location = /image404.html {
        #  The image does not exist to return specific information 
        return 404 "image not found\n";
    }
}

To form such as/images ef/uh7b3 / test png request, rewritten to/data & # 63; file = test png, so match to location/data, see first/data images/test png file does not exist, if there is a normal response, if there is no rewrite tryfiles to new image404 location, direct return 404 status code.

Example 2:


rewrite ^/images/(.*)_(\d+)x(\d+)\.(png|jpg|gif)$ /resizer/$1.$4?width=$2&height=$3? last;

For file requests in the form of /images/ bla_500x400.jpg, rewrite to /resizer/ bla.jpg ? width=500&height=400 addresses, and will continue to try to match location.

The above is the nginx configuration location summary location regular writing and rewrite rules writing, the following related articles have more about nginx configuration introduction article hope to help you


Related articles: