Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Detailed explanation of nginx configuration location summary and rewrite rule writing

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/02 Report--

Location regular writing method

An example:

Location = / {# exact match /, the hostname cannot be followed by any string [configuration A]} location / {# because all addresses begin with /, so this rule will match all requests # but regular and longest strings will match [configuration B]} location / documents/ {# to match any address that starts with / documents/, matching later Continue to search # this line will use this [configuration C]} location ~ / documents/Abc {# to match any address that begins with / documents/ only if the following regular expression does not match. After the match, continue to search # when only the following regular expression does not match This one will use this [configuration CC]} location ^ ~ / images/ {# to match any address that starts with / images/. After the match, stop searching for regularities and use this one. [configuration D]} location ~ *\. (gif | jpg | jpeg) ${# matches all requests ending with gif,jpg or jpeg # however, images under all requests / images/ are processed by config D because ^ ~ cannot reach the regular [configuration E]} location / images/ {# characters match to / images/, to continue You will find that ^ ~ has [configuration F]} location / images/abc {# longest character matching to / images/abc. If you go on, you will find that ^ ~ exists # F has nothing to do with the order in which G is placed. [configuration G]} location ~ / images/abc/ {# is valid only if you remove config D: first, the longest match the address at the beginning of config G, and then continue to search to find this rule. Use [configuration H]} location ~ * / js/.*/\ .js to indicate an exact match at the beginning of =. For example, An only matches the request at the end of the root directory and cannot be followed by any string. The beginning of ^ ~ means that uri starts with a regular string, not a regular match. The beginning of ~ indicates a case-sensitive regular match; the beginning of ~ * indicates a case-insensitive regular match / universal match. If there is no other match, any request will match to the

Sequential no priority:

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

The matching results above

According to the location above, the following matching example holds:

/-> config A: exact match, even / index.html cannot match / downloads/download.html-> config B: after matching B, there is no match down. Use B/images/1.gif-> configuration D: match to F, match down to D, stop / images/abc/def-> config D: the longest match to G, match D down, stop going down. You can see that anything that starts with / images/ will match to D and stop. FG doesn't make any sense here, and H will never turn. Here is just to illustrate the matching order / documents/document.html-> config C: match to C, no match down, use C/documents/1.jpg-> configuration E: match to C, go down regular match to E/documents/Abc.jpg-> config CC: longest match to C. Down regular order matches to CC, not down to E

Suggestions for practical use

Therefore, in actual use, I think there are at least three matching rule definitions, as follows:

# directly match the root of the website, and visit the home page of the website more frequently through the domain name. Using this will speed up the processing, according to the official website. # this is forwarded directly to the backend application server, or it can be a static home page # the first required rule location = / {proxy_pass http://tomcat:8080/index}# the second required rule is to handle static file requests, which is the strength of nginx as a http server # there are two configuration modes, directory matching or suffix matching, choose either or use location ^ ~ / static/ {root/ webroot/static/ } location ~ *\. (gif | jpg | jpeg | png | css | 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 requests are dynamic requests by default, according to the actual grasp. # after all, in some current frameworks, there are few location / {proxy_pass http://tomcat:8080/} suffixes with .php and .jsp suffixes

Http://nginx.org/en/docs/http/ngx_http_rewrite_module.html

Rewrite rule

The function of rewrite is to use global variables provided by nginx or variables set by yourself, combined with regular expressions and flag bits to achieve 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 overrides / a/we/index.php. Syntax rewrite regex replacement [flag]

If relative domain names or parameter strings work, you can use global variable matching or proxy_pass reverse proxies.

It shows that the functions of rewrite and location are similar, and both can be redirected. The main difference is that rewrite changes the path to obtain resources within the same domain name, while location controls access or reverse proxies for a class of paths, and can proxy_pass to other machines. In many cases, rewrite is also written in location, and the order in which they are executed is:

Execute rewrite instruction of server block execute location match execute rewrite instruction in selected location

If one of the steps URI is rewritten, cycle through 1-3 until a real file is found; if you loop more than 10 times, a 500Internal Server Error error is returned.

Flag marker bit

Last: equivalent to the [L] tag of Apache, indicating completion of rewritebreak: stop executing the subsequent rewrite instruction set of the current virtual host redirect: return 302 temporary redirection, the address bar will display the jump address permanent: return 301 permanent redirection, the address bar will display the jump address

Because 301 and 302 cannot simply return the status code, they must also have a redirected URL, which is why the return instruction cannot return 301302. Here the difference between last and break is a little hard to understand:

Last is generally written in server and if, while break generally uses url matching after last without terminating rewriting in location, that is, the new url will go through the matching process from server again, while both break and last after break termination rewriting can organize and continue to execute the following rewrite instructions.

If directive and global variable

If judgment instruction

The syntax is if (condition) {...} to determine 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 a variable, if the value is empty or any string that begins with 0 will be used as a false to directly compare variables and contents, use = or! = ~ regular expression matching, ~ * case-insensitive matching,! ~ case-sensitive mismatch

-f and!-f are used to determine whether a file exists.

-d and!-d are used to determine whether a directory exists.

-e and!-e are used to determine whether a file or directory exists

-x and!-x are used to determine whether the file is executable or not

For example:

If ($http_user_agent ~ MSIE) {rewrite ^ (. *) $/ msie/$1 break;} / / if UA contains "MSIE", rewrite requests to if ($http_cookie ~ * "id= ([^;] +) (?; | $)") {set $id $1;} / if cookie matches regular, set variable $id equal to regular reference part if ($request_method = POST) {return 405 } / / if the submit method is POST, status 405 (Method not allowed) is returned. Return cannot return 301302if ($slow) {limit_rate 10k;} / / speed limit, and $slow can 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. The break here also stops rewrite checking if ($args ~ post=140) {rewrite ^ http://example.com/ permanent;} / / if the query string contains "post=140", permanently redirect to example.comlocation ~ *\. (gif | jpg | png | swf | flv) ${valid_referers none blocked www.jefflei.com www.leizhenfang.com; if ($invalid_referer) {return 404;} / / hotlink protection}

Global variable

Here are the global variables that can be used as if judgments

$args: # this variable is equal to the parameter in the request line, the same as the $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: request the host header field, otherwise it is 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: the port of the client. Remote_user: the user name that has been authenticated by Auth Basic Module. Request_filename: the file path of the current request, generated by the root or alias directive and the URI request. $scheme: the HTTP method (such as http,https). Server_protocol: the protocol used by the request, usually HTTP/1.0 or HTTP/1.1. $server_addr: server address, which can be determined after completing a system call. $server_name: server name. Server_port: the port number on which the request arrives at the server. $request_uri: the original URI containing the request parameters, without the hostname, such as "/ foo/bar.php?arg=baz". $uri: the current URI,$uri without request parameters does not contain a hostname, 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

Commonly used regularity

. : match any character except newline character?: repeat 0 or 1 time +: repeat 1 or more times *: repeat 0 or more times\ d: match number ^: start of matching string $: introduction to matching string {n}: repeat n times {n Repeat n or more times [c]: match a single character c [a-z]: any one of the lowercase letters of amurz

The matching between parentheses () can be referenced later by $1, and $2 represents the content in the second () above. What is confusing in the rule is the escape of special characters.

Rewrite instance

Example 1:

Http {# define 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 quotation marks to avoid {} rewrite'^ / images/ ([a murz] {2}) / ([a-z0-9] {5}) / (. *)\. (png | jpg | gif) $'/ data?file=$3.$4; # Note that you cannot add the parameter "last" after the above rule, otherwise the following set instruction will not execute set $image_file $3 Set $image_type $4;} location / data {# specifies the log format for the image to analyze the image type and size access_log logs/images.log mian; root / data/images; # applies the previously defined variables. Determine whether the first file is present, and then determine whether the directory is there. If not, jump to the last url try_files / $arg_file / image404.html;} location = / image404.html {# Picture does not exist. Return specific information return 404 "image not found\ n";}}

For requests such as / images/ef/uh7b3/test.png, rewrite to / data?file=test.png, so match to location / data to see if the / data/images/test.png file exists, and respond normally if it does not exist. If it does not exist, rewrite the tryfiles to the new image404 location, and directly return the 404 status code.

Example 2:

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

For file requests such as / images/bla_500x400.jpg, rewrite to the / resizer/bla.jpg?width=500&height=400 address and continue to try to match the location.

Example 3:

See ssl part of the page encryption.

The above is the whole content of this article, I hope it will be helpful to your study, and I also hope that you will support it.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report