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

How to use location and rewrite in nginx

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

Share

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

This article is to share with you about how location and rewrite are used in nginx. The editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.

Summary of the usage of location

Location can locate different requests to different processing methods.

The usage of 1.location

Location ~ * / js/.*/\ .js

It starts with = to indicate an exact match; if only a request that matches the end of the root directory, it cannot be followed by any string.

Starting with ^ ~ means that uri starts with a regular string and is not a regular match.

Starts with ~ to indicate a case-sensitive regular match

Starts with ~ * to indicate a case-insensitive regular match

Starts with /, universal matching, if there is no other match, any request will match

The matching order of location is "match regular first, then match normal".

Correction: the matching order of location is actually "match normal first, then match regular". If I say so, you will certainly refute me, because pressing "match ordinary first, then match regular" does not explain the practical experience of "matching regular first, then matching ordinary". I can only explain for the time being that the reason for this misunderstanding is that regular matches will override normal matches.

Examples of 2.location usage

Location canonical writing:

1. # exact match /. The host name cannot be followed by any string.

Location = / {[configuration A]}

2.# all addresses start with /, so this rule will eventually match to the default request

# but regular and longest strings match location / {[configuration B]} first

Example:

The rule location / {proxy_pass http://server_pools;} # can be matched only if other rules do not meet the requirements; it will be the last match, with the lowest degree of matching. The above functions are: for example, when the website does not enter anything after www.blog.com;, and other rules do not match, it will be finally handed over to the server in the load balancing pool.

3.# match any address that starts with / documents/. After matching, continue to search.

# this location / documents/ {[configuration C]} will be used only if the following regular expressions do not match.

Example:

Location / static/ {rewrite ^ http://www.abc.com;} # function implemented above: if the website domain name is www.blog.com;, then the above function is to enter www.blog.com/static/, no matter what page is behind the static (the page may not exist), then it will also jump to the www.abc.com website eventually.

4.# match any address that starts with / documents/. After matching, continue to search.

# this line will be used only if the latter regular expression does not match.

Location ~ / documents/Abc {[configuration CC]}

5.# match any address that starts with / images/. After the match, stop searching for rules and use this one.

Location ^ ~ / images/ {[configuration D]}

6.# match all requests that end in gif,jpg or jpeg

# however, all pictures under the request / images/ will be processed by config D because ^ ~ cannot reach this rule

Location ~ *\. (gif | jpg | jpeg) ${[configuration E]}

Example:

7.# characters match to / images/, continue, you will find ^ ~ exists

Location / images/ {[configuration F]}

8.# the longest character matches to / images/abc. If you go further, you will find that ^ ~ exists.

# F has nothing to do with the placement order of G

Location / images/abc {[configuration G]}

9.# it is only valid if config D is removed: first, match the address starting with config G as the longest, then continue to search, and match to this rule, using

Location ~ / images/abc/ {[configuration H]}

Sequential no priority:

(location =) > (location full path) > (location ^ ~ path) > (location ~, ~ * regular order) > (location partial start path) > (/) the matching result above:

According to the above location writing, the following matching example holds: /-> config An exact match, even / index.html can not match / downloads/download.html-> config B match B, there is no match down, use B/images/1.gif-> configuration D to match F, down to D, stop down / images/abc/def-> config D to G, and match D down If you stop going down, you can see that anything that starts with / images/ will match to D and stop. It doesn't make any sense for FG to write here, and H will never turn. Here is just to show that the matching order / documents/document.html-> config C matches C, and there is no match down. Use C/documents/1.jpg-> configuration E to match C, and down regular match to E/documents/Abc.jpg-> config CC the longest match to C. Down regular order matches to CC, not down to E

3. 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 | 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 requests are dynamic requests by default, according to the actual grasp of # after all, the popularity of some current frameworks Location / {proxy_pass http://tomcat:8080/}http://tengine.taobao.org/book/chapter_02.htmlhttp://nginx.org/en/docs/http/ngx_http_rewrite_module.html is rare in cases with .php and .jsp suffixes

II. Summary of Rewrite usage

Definition of 1.rewrite

The rewrite function 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 rewrites / a/we/index.php.

Syntax of 2.rewirte

Rewrite regex replacement [flag]

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

From the above shows that rewrite and location function is a bit like, can achieve jump. 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:

1 execute the rewrite instruction of the server block

2 perform location matching

3 execute the rewrite instruction in the 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 that the rewrite is complete

Break: stops executing the subsequent rewrite instruction set of the current virtual host

Redirect: returns 302 temporary redirection. The address bar will display the address after the jump.

Permanent: returns 301 permanent redirection, and the address bar will display the address after the jump.

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 is generally used in location

Last does not terminate the rewritten url match, that is, the new url goes through the matching process from server again, while break terminates the rewritten match.

Both break and last can organize and continue to execute the following rewrite instructions

Regularization is often used in 3.rewrite.

. Match any character except the newline character

?: repeat 0 or 1 times

+: repeat 1 or more times

*: repeat 0 or more times

\ d: match the number

^: match the beginning of the string

$: the end of the matching string

{n}: repeat n times

{n,}: repeat n or more times

[C]: matches a single character c

[amurz]: matches any 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 {# defines the image log format log_format imagelog'[$time_local]'$image_file''$image_type''$body_bytes_sent''$status;# to enable 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: do not add the "last" parameter to the above rule, otherwise the following set instruction will not execute set $image_file $3tset $image_type $4. } location / data {# specifies the log format for the picture to analyze the image type and size access_log logs/images.log mian;root / data/images;# to apply the previously defined variables. Determine whether the first file is there, 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. For example, 2:rewrite ^ / images/ (. *) _ (\ d +) x (\ d +)\. (png | jpg | gif) $/ resizer/$1.$4?width=$2&height=$3? Last; rewrites requests for files such as / images/bla_500x400.jpg to the / resizer/bla.jpg?width=500&height=400 address and continues to try to match location.

If directive and global variable

If judgment instruction syntax

If (condition)

{...}

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 a variable, if the value is empty or any string that begins with 0 will be treated as false

When comparing variables and contents directly, 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

Example:

If the user device is an IE browser, redirect if ($http_user_agent ~ MSIE) {rewrite ^ (. *) $/ msie/$1 break;} / / if UA contains "MSIE", rewrite requests to if under / msid/ directory ($http_cookie ~ * "id= ([^;] +) (?:; | $)") {set $id $1 } / / if the cookie matches regular, the setting variable $id equals the regular reference part if ($request_method = POST) {return 405;} / / returns status 405 (Method not allowed) if the submit method is POST. Return cannot return 301302 if ($slow) {limit_rate 10k;} / / speed limit, $slow can set if (!-f $request_filename) {break;proxy_pass http://127.0.0.1;} / / reverse proxy to localhost if the requested file name does not exist. 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.com location ~ *\. (gif | jpg | png | swf | flv) ${valid_referers none blocked www.jefflei.comwww.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, 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: 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 request_uri: http://localhost:88/test1/test2/test.php$document_uri stop Test1 stop Test2 stop test.phpgram documentationrootVar stop WWG htmlrequestenameGetRequestenameWhere is how location and rewrite are used in nginx. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

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