Detailed explanation of nginx configuration location and rewrite rules

1. Location regular writing

 

Syntax rules: location [=|~|~*|^~] /uri/ { … }
= starts with an exact match
The beginning of ^~ means that the uri starts with a regular string, which can be understood as matching the url path. nginx does not encode URLs, so the request is /static/20%/aa, which can be matched by the rule ^~ /static/ /aa (note the space).
~ starts with a case-sensitive regular match
~* at the beginning means case-insensitive regular matching
!~ and !~* are case -sensitive mismatches and case -insensitive mismatches  , respectively
/ Universal match, any request will match.
In the case of multiple location configurations, the matching order is (from the reference material, it has not been verified yet, just try it, you don't have to be rigid, it is for reference only):
First matches =, second matches ^~, second is regular matching in the order in the file, and finally is handed to / for general matching. When there is a successful match, stop matching and process the request according to the current matching rules.

 

For example, there are the following matching rules:

location = / {  
   #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:
Accessing the root directory/, such as http://localhost/ will match rule A
Accessing http://localhost/login will match rule B, and http://localhost/register will match rule H
Visiting http://localhost/static/a.html will match rule C
Visiting http://localhost/a.gif, http://localhost/b.jpg will match rule D and rule E, but rule D takes precedence, rule E does not work, and http://localhost/static/c .png matches rule C first
Visiting http://localhost/a.PNG matches rule E, but not 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 rules but will not match, so think about where they 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 direction proxy server.
Therefore, in actual use, there are usually at least three matching rules defined, as follows:
 
#Directly match the root of the website. It is more frequent to visit the homepage of the website through the domain name. 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  
# first required 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 the general rule, which is used to forward dynamic requests to the back-end application server  
#Non-static file request is a dynamic request by default, and you can grasp it according to the actual situation  
#After all, some of the current frameworks are popular, and there are very few cases with .php,.jsp suffixes  
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 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 for the passed parameters, for example,  http://seanlook.com/a/we/index.php?id=1&u=str only rewrite /a/we/index.php. grammarrewrite 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 is also written in the location, and their execution order is:

  1. Execute the rewrite instruction of the server block
  2. perform location matching
  3. Execute the rewrite command in the selected location

If the URI is rewritten in one of the steps, 1-3 will be repeated until the real file is found; if the loop exceeds 10 times, a 500 Internal Server Error will be returned.

2.1 flag flag bit

  • last : Equivalent to Apache's [L] tag, indicating completion of rewrite
  • break : Stop executing the subsequent rewrite instruction set of the current virtual host
  • redirect : Return to 302 temporary redirection, the address bar will display the redirected address
  • permanent : Return to 301 permanent redirect, the address bar will display the redirected address

Because 301 and 302 cannot simply return the status code, there must also be a redirected URL, which is why the return command cannot return 301, 302. The difference between last and break here is a little hard to understand:

  1. Last is generally written in server and if, while break is generally used in location
  2. last does not terminate the rewritten url matching, that is, the new url will go through the matching process from the server again, and break terminates the rewritten matching
  3. Both break and last can organize and continue to execute subsequent rewrite instructions

2.2 if directive and global variables


The syntax of the if judgment instructionif(condition){...} is to judge 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 comparing variables and content directly, use =or!=
  • ~Regular expression match, ~*case-insensitive match, !~case-sensitive mismatch

-fand !-fis used to determine whether a file exists
-dand !-dis used to determine whether a directory exists
-eand !-eis used to determine whether a file or directory exists
-xand is used to determine whether a !-xfile is executable

E.g:

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
}

  

Global variables
Below are global variables that can be used as if judgments

  • $args : #This variable is equal to the parameter 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 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.
  • $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 completing a system call.
  • $server_name : server nickname.
  • $server_port : The port number on which the request arrives at the server.
  • $request_uri : Contains the original URI of 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, eg "/foo/bar.html".
  • $document_uri : same as $uri.

例: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 rules

  • . : matches any character except newline
  • ? : Repeat 0 or 1 time
  • + : Repeat 1 or more times
  • * : Repeat 0 or more times
  • \d : matches numbers
  • ^ : matches the beginning of the string
  • $ : Introduction to matching strings
  • {n} : repeat n times
  • {n,} : Repeat n or more times
  • [c] : matches a single character c
  • [a-z] : matches any of the lowercase letters of az

()The content matched between the parentheses can $1be referenced later by $2means of the content in the second one ()in front. The most confusing part of regex is \escaping special characters.

2.4 rewrite instance

Example 1 :

http {
    # Define the image log format
    log_format imagelog '[$time_local] ' $image_file ' ' $image_type ' ' $body_bytes_sent ' ' $status;
    # Enable rewrite log
    rewrite_log on;

    server {
        root /home/www;

        location / {
                # Rewrite rule information
                error_log logs/rewrite.log notice;
                # Note that you should use '' single quotes here, avoid {}
                rewrite '^/images/([a-z]{2})/([a-z0-9]{5})/(.*)\.(png|jpg|gif)$' /data?file=$3.$4;
                # Note that the "last" parameter cannot be added after the above rule, otherwise the following set command 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 variables defined earlier. Judging whether the file exists first, and then judge whether the directory exists, if not, jump to the last url
                try_files /$arg_file /image404.html;
        }
        location = /image404.html {
                # Image does not exist return specific information
                return 404 "image not found\n";
        }
}

  

For /images/ef/uh7b3/test.pngthe request of the form, rewrite it /data?file=test.png, so it matches location /data, first see /data/images/test.pngif the file exists, if it exists, it will respond normally, if it does not exist, rewrite tryfiles to the new image404 location, and return the 404 status code directly.

Example 2 :

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

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

Example 3 :
See  ssl section page encryption  .

refer to

 

Retrieved from http://seanlook.com/2015/05/17/nginx-location-rewrite/

Guess you like

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