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 configure location for nginx

2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

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

Editor to share with you how to configure nginx location, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

1. Location regular writing

First, let's look at 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/Abc 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

Location prefix

No prefix matches location that begins with the specified pattern

= exact match, not starting with the specified pattern

~ regular matching, case sensitive

~ * regular matching, case-insensitive

^ ~ irregular match, matching location that starts with the specified pattern

/ Universal match, if there is no other match, any request will match to

Location matching order

Multiple regular location matches directly according to the writing order. After success, they will not continue to match.

Normal (irregular) location will go down until the best match is found (maximum prefix match)

When normal location and regular location exist at the same time, if regular matching is successful, normal matching will not be performed.

When all types of location exist, "=" match > "^ ~" match > regular match > normal (maximum prefix match)

Order:

(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, not even / index.html match

/ downloads/download.html-> config B

After matching B, there is no match down, using B.

/ images/1.gif-> configuration D

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

/ images/abc/def-> config D

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, H will never come, just to illustrate the matching order.

/ documents/document.html-> config C

Match to C, there is 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 match 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

2. Rewrite rules

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://jb51.net/a/we/index.php?id=1&u=str only rewrites / 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 instructions for server blocks

Perform location matching

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.

2.1 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

2.2 if directives and global variables

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 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

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;} / / 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.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, 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: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

. 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

$: introduction to matching strings

{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.

2.4 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.

These are all the contents of the article "how to configure location for nginx". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to 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