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 and rewrite rules for Nginx

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

Share

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

This article mainly explains "how to configure location and rewrite rules in Nginx". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to configure location and rewrite rules in Nginx".

Location tutorial

Example:

Location = / {# exact match /, the hostname cannot be followed by any string [configuration A]} location / {# because all addresses begin with /, all 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/ After the match, continue to search # only if the subsequent regular expression does not match, this entry will use [configuration C]} location ~ / documents/Abc {# to match any address that begins with / documents/. After the match, continue to search # when only the following regular expression does not match Will use this [configuration CC]} location ^ / images/ {# to match any address that begins with / images/. After the match, stop searching for regularities, and use this [configuration D]} location ~ *\. (gif | jpg | jpeg) ${# to match all requests ending in gif,jpg or jpeg # however, the image under Su friend's request / images/ will be processed by config D. Because ^ ~ cannot reach this regular [configuration E]} location / images/ {# character match to / images/, continue, you will find that ^ ~ exists [configuration F]} location / images/abc {# longest character match to / images/abc, continue 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 match the address at the beginning of config G as the longest, then continue to search for this rule, and use [configuration H]} location ~ * / js/.*/\ .js.

Start with = to indicate an exact match. For example, in A, only the request at the end of the root directory is matched, and no string can be followed.

The beginning of ^ ~ means that uri begins with a regular string and is not a regular match.

~ begins with 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

Order & & priority

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

Suggestions for practical use

# there are at least three matching rule definitions, as follows:

# directly match the root of the website. Visit the home page of the website frequently through the domain name. Using this will speed up the processing.

# forward it 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. Nginx is the strength of the http server

# there are two configuration modes, directory matching or suffix matching, either or in combination

Location ^ ~ / static/ {root/ webroot/static/;} location ~ *\. (gif | jpg | jpeg | png | css | js | ico) ${root/ webroot/res/;}

# the third rule is a general rule, which is used to forward dynamic request channel back-end application servers

Location / {proxy_pass http://tomcat:8080/}Rewrite tutorial

Function: 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 passing 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 you want to work on domain names or parameter strings, you can use global variable matching or you can use proxy_pass reverse proxies.

Similarities and differences between rewrite and location: both can be redirected; different: rewrite changes the path to obtain resources within the same domain name, while location controls access or reverse proxies for another type of path, and can proxy_pass to other machines.

Execution order:

Rewrite instruction for server block

Location matching

Select the rewrite instruction in location, and if one of the steps url is rewritten, the rewrite loop executes 1-3 until the real file is found; if the loop is 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 301and302cannot simply return the status code, there must also be a redirected URL, which is why the return instruction cannot return 301302

Similarities and differences between last and break:

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

If instruction and global variable if judgment instruction

Syntax: if (condition) {...} to judge the given condition condition. If true, the rewrite instruction in curly braces will be executed, and the if condition (condition) 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

To directly compare variables with content, use = or! =

~ regular expression matching, ~ * case-insensitive matching,! ~ 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! -x is used to determine whether the file can be executed

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 the regular, set the variable $id equal to the regular reference part if ($request_method = POST) {return 405 } # if it is mentioned that the method is POST, status 405 (Method not allowed) is returned. Return cannot return 301302if ($slow) {limit_rate 10k;} # speed limit, $slow can set if (!-f $request_filename) {break; proxy_pass http://127.0.01;} # 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 parameters in the request line, same as $query_string

$content_length: the Conten-length field in the request header

$content_type: the Content-Type field in the request header

$document_root: request the value specified in the root directive

$host: request host header field, otherwise it is the server name

$http_user_agent: client agent information

$http_cookie: client cookie information

$limit_rate: limit the connection rate

$request_method: the action requested by the client, usually GET or POST

$remote_addr: IP address of the client

$remote_port: client port

$remote_user: 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 URL request

$scheme:HTTP method (such as http,https)

$server_protocol: the protocol used for 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 reaches the server

$request_url: the original url containing the request parameters, without the hostname, such as "/ foo/bar.php?arg=baz"

$url: the current url,$url without request parameters does not contain a hostname, such as "/ foo/bar.html"

$document_url: same as $url

Example: http://localhost:88/test1/test2/test.php

$host:localhost

$server_port:88

$request_url: http://localhost:88/test1/test2/test.php

$document_url:/test1/test2/test.php

$document_root:/var/www/html

$request_filename:/var/www/html/test1/test2/test.php

Commonly used regularity

.: matches any character except the newline character

?: repeat 0 or 1 times

+: repeat 1 or more times

*: repeat one or more times

\ d: match the number

^: match the beginning of the string

$: the end of the matching character

{n}: repeat n times

{n,}: repeat n or more times

[C]: matches a single character c

[amurz]: any parenthesis () that matches the lowercase letters of amurz can be referenced later by $1, and $2 represents the content in the previous second (). The perplexing part of 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 the "last" parameter cannot be added 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 picture to analyze the image type and size access_log logs/images.log main; root / data/images; # applies the variables defined earlier. First of all, determine whether the file is there, and then determine whether the directory is there. If it is not in 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 location

Thank you for reading, the above is the content of "how to configure location and rewrite rules for Nginx". After the study of this article, I believe you have a deeper understanding of how to configure location and rewrite rules for Nginx, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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

*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

Development

Wechat

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

12
Report