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

What are the rules of Nginx forwarding matching

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

Share

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

This article introduces the relevant knowledge of "what are the rules of Nginx forwarding matching". In the operation of actual cases, many people will encounter such a dilemma. Then let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Regular expression matching

~ for case-sensitive matching

~ * for case-insensitive matching

! ~ and! * are case-sensitive mismatch and case-insensitive mismatch, respectively

II. Matching of files and directories

-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

3. The last parameter of the rewrite instruction is the flag tag, and the flag tag has

Last is equivalent to the [L] tag in apache and stands for rewrite.

Break after the matching of this rule is completed, the matching is terminated and the subsequent rules are no longer matched.

Redirect returns 302 temporary redirection, and the browser address displays the URL address after the jump.

Permanent returns 301 permanent redirection, and the browser address displays the URL address after the jump.

URI rewriting is implemented using last and break, and the browser address bar remains unchanged.

And there is a slight difference between the two: using the alias instruction must be marked with last; when using the proxy_pass instruction, you need to use the break tag. After the implementation of this rewrite rule, the Last tag will re-initiate the request for its server {.} tag, while the break tag will terminate the matching after the completion of the matching of this rule.

For example, if we redirect something like URL/photo/123456 to / path/to/photo/12/1234/123456.png

Rewrite "/ photo/ ([0-9] {2}) ([0-9] {2}) ([0-9] {2})" rewrite "/ path/to/photo/$1/$1 $2 3.png"; IV. Instructions related to NginxRewrite rules

1. Break instruction

Use environment: server, location, if

The purpose of this instruction is to complete the current rule set and no longer process the rewrite instruction.

2. If instruction

Use environment: server, location

This directive is used to check whether a condition is met and, if so, to execute the statement in curly braces. If directives do not support nesting and multiple conditions & & and | | processing.

3. Return instruction

Syntax: returncode

Use environment: server, location, if

This instruction is used to end the execution of the rule and return the status code to the client.

Example: if the accessed URL ends with ".sh" or ".bash", a 403 status code is returned

Location. *\. (sh | bash)? ${return 403;}

4. Rewrite instruction

Syntax: rewriteregex replacement flag

Use environment: server, location, if

This instruction redirects the URI based on the expression, or modifies the string. Instructions are executed according to the order in the configuration file. Note that rewriting expressions are only valid for relative paths. If you want to pair hostnames, you should use the if statement, as shown in the following example:

If ($host ~ * www\. (. *)) {set $host_without_www $1; rewrite ^ (. *) $http://$host_without_www$1permanent;}

5. Set instruction

Syntax: setvariable value; default value: none environment: server, location, if

This instruction is used to define a variable and assign a value to the variable. The value of a variable can be a combination of text, variables, and text variables.

Set$varname "hello world"

6. Uninitialized_variable_warn instruction

Syntax: uninitialized_variable_warnon | off

Use environment: http, server, location, if

This directive is used to turn on and off warnings for uninitialized variables. The default value is on.

5. Rewrite rule writing example of Nginx

1. Redirect to a html file when the accessed file and directory do not exist

If (!-e $request_filename) {rewrite ^ / (. *) $index.htmllast;}

2. Directory swap / 123456/xxxx = = > / xxxx?id=123456

Rewrite ^ / (\ d +) /. + / / $2?id=$1 last

3. If the client is using an IE browser, redirect to the / ie directory

If ($http_user_agent ~ MSIE) {rewrite ^ (. *) $/ ie/$1 break;}

4. Prohibit access to multiple directories

Location ~ ^ / (cron | templates) / {deny all; break;}

5. Disable access to files starting with / data

Location ~ ^ / data {deny all;}

6. Prohibit access to files with .sh, .flv, .mp3 suffixes.

Location ~. *\. (sh | flv | mp3) ${return 403;}

7. Set the browser cache time for some types of files

Location ~. *\. (gif | jpg | jpeg | png | bmp | swf) ${expires 30d;} location ~. *\. (js | css) ${expires 1h;}

8. Set the expiration time for favicon.ico and robots.txt

Here, favicon.ico is 99 days, robots.txt is 7 days and 404 error logs are not recorded.

Location ~ (favicon.ico) {log_not_found off; expires 99d; break;} location ~ (robots.txt) {log_not_found off; expires 7d; break;}

9. Set the expiration time of a file. Here it is 600 seconds, and no access log is recorded.

Location ^ ~ / html/scripts/loadhead_1.js {access_log off; root / opt/lampp/htdocs/web; expires 600; break;}

10. File anti-hotlink and set expiration time

The return412 here is a custom http status code. The default is 403. It is easy to find the correct hotlink request.

Rewrite ^ / http: / / img.linuxidc.net/leech.gif;// displays a hotlink protection picture access_log off; / / reduces the pressure on expires 3D / / browser cache location * ^. +\. For all files for 3 days. (jpg | jpeg | gif | swf | zip | css | js) ${valid_referers none blocked * .linuxidc.com*.linuxidc.net localhost 208.97.167.194 if ($invalid_referer) {rewrite ^ / http://img.linuxidc.net/leech.gif; Return 412; break;} access_log off;root / opt/lampp/htdocs/web;expires 3D

11. Only fixed ip is allowed to access the website with a password

Root / opt/htdocs/www;allow 208.97.167.194; allow 222.33.1.2; allow 231.152.49.4 deny all;auth_basic "C1G_ADMIN"; auth_basic_user_file htpasswd

12. Convert the files in multi-level directories into one file to enhance the seo effect.

/ job-123-456-789.html points to / job/123/456/ 789.htmlrewrite^ / job- ([0-9] +)-([0-9] +)-([0-9] +)\ .html$ / job/$1/$2/jobshow_$3.html last

13. Redirect when files and directories do not exist:

If (!-e $request_filename) {proxy_pass http://127.0.0.1;}

14. Point a folder under the root directory to a level 2 directory

If / shanghaijob/ points to / area/shanghai/, if you change last to permanent, the browser address bar says / location/shanghai/rewrite ^ / ([0-9a-z] +) job/ (. *) $/ area/$1/$2last;. One problem with the above example is that accessing / shanghai will not match rewrite ^ / ([0-9a-z] +) job$ / area/$1/ last;rewrite ^ / ([0-9a-z] +) job/ (. *) $/ area/$1/$2last. In this way, / shanghai can also be accessed, but the relative links in the page cannot be used, for example, the real address of. / list_1.html / area/shanghia/list_1.html becomes / list_1.html, leading to inaccessibility. Then I can't add automatic jump (- d $request_filename) it has a condition that it must be a real directory, but my rewrite is not, so there is no effect if (- d $request_filename) {rewrite ^ / (. *) ([^ /]) $http://$host/$1$2/permanent;} knows why, let me jump manually rewrite ^ / ([0-9a-z] +) job$ / $1job/permanent Rewrite ^ / ([0-9a-z] +) job/ (. *) $/ area/$1/$2last

15. Domain name jump

Server {listen 80; server_name jump.linuxidc.com; index index.html index.htm index.php; root / opt/lampp/htdocs/www; rewrite ^ / http://www.linuxidc.com/; access_log off;}

16. Multi-domain name shift

Server_name www.linuxidc.comwww.linuxidc.net;index index.html index.htm index.php;root / opt/lampp/htdocs;if ($host ~ "linuxidc\ .net") {rewrite ^ (. *) http://www.linuxidc.com$1permanent;} VI, nginx global variable arg_PARAMETER # this variable contains the value in the GET request, if there is a variable PARAMETER. The variable args # is equal to the parameters in the request line (GET request), such as the foo=123&bar=blahblah;binary_remote_addr # binary customer address. The number of body bytes sent out in the body_bytes_sent # response. Even if the connection is broken, this data is accurate. The Content-length field in the content_length # request header. The Content-Type field in the content_type # request header. The value of the cookie_COOKIE # cookie COOKIE variable document_root # currently requests the value specified in the root directive. Document_uri # is the same as uri. Host # requests the host header field, otherwise it is the server name. Hostname # Set to themachine's hostname as returned by gethostnamehttp_HEADERis_args # if there is an args parameter, this variable is equal to "?", otherwise equal to "", a null value. Http_user_agent # client agent information http_cookie # client cookie information limit_rate # this variable can limit the connection rate. Query_string # is the same as args. The temporary file name of the request_body_file # client request principal information. The action requested by the request_method # client, usually GET or POST. The IP address of the remote_addr # client. Port of the remote_port # client. Remote_user # user name that has been authenticated by Auth Basic Module. Request_completion # if the request ends, set it to OK. Null (Empty) when the request is not completed or if it is not the last in the request chain. The file path currently requested by request_method # GET or POSTrequest_filename #, generated by the root or alias directive and the URI request. Request_uri # contains the original URI of the request parameter, without the hostname, such as "/ foo/bar.php?arg=baz". It can't be modified. Scheme # HTTP method (such as http,https). The protocol used by the server_protocol # 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. The port number that the server_port # request arrives at the server.

# VII. Correspondence between Apache and Nginx rules

Apache's RewriteCond corresponds to Nginx's ifApache's RewriteRule corresponds to Nginx's rewriteApache's [R] corresponds to Nginx's redirectApache's [P] corresponds to Nginx's lastApache's [RMagol L] corresponds to Nginx's redirectApache's [PMagol L] corresponds to Nginx's lastApache's [PT,L] corresponds to Nginx's last.

For example, the specified domain name is allowed to access this site, and all other domain names are transferred to www.linuxidc.net.

Apache:RewriteCond% {HTTP_HOST}! ^ (. *?)\ .aaa\ .com $[NC] RewriteCond% {HTTP_HOST}! ^ localhost$ RewriteCond% {HTTP_HOST}! ^ 192\ .168\ .0\. (. *?) $RewriteRule ^ / (. *) $http://www.linuxidc.net[R,L]

Example of Nginx filtering:

If ($host ~ * ^ (. *)\ .aaa\ .com $) {set $allowHost '1percent;} if ($host ~ * ^ localhost) {set $allowHost' 1percent;} if ($host ~ * ^ 192\ .168\ .1\. (. *?) $) {set $allowHost '1percent;} if ($allowHost! ~' 1') {rewrite ^ / (. *) $http://www.linuxidc.netredirect } this is the end of the content of "what are the Nginx forwarding matching rules". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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

Development

Wechat

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

12
Report