1. Location regular writing
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 }
#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:
- Execute the rewrite instruction of the server block
- perform location matching
- 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 rewritebreak
: Stop executing the subsequent rewrite instruction set of the current virtual hostredirect
: Return to 302 temporary redirection, the address bar will display the redirected addresspermanent
: 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:
- Last is generally written in server and if, while break is generally used 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, and break terminates the rewritten matching
- 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
-f
and !-f
is used to determine whether a file exists -d
and !-d
is used to determine whether a directory exists -e
and !-e
is used to determine whether a file or directory exists -x
and is used to determine whether a !-x
file 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 $1
be referenced later by $2
means 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.png
the request of the form, rewrite it /data?file=test.png
, so it matches location /data
, first see /data/images/test.png
if 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.jpg
file requests of the form, rewrite to the /resizer/bla.jpg?width=500&height=400
address, and will continue to try to match the location.
Example 3 :
See ssl section page encryption .
refer to
- http://www.nginx.cn/216.html
- http://www.ttlsa.com/nginx/nginx-rewriting-rules-guide/
- The rewrite rules of the old monk series nginx get started quickly
- http://fantefei.blog.51cto.com/2229719/919431
Retrieved from http://seanlook.com/2015/05/17/nginx-location-rewrite/