In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)06/01 Report--
This article will explain in detail the implementation of forwarding matching rules in Nginx. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.
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
Use 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; / / does not record access logs, reducing pressure expires 3D / / browser cache location ~ * ^. +\. (jpg | jpeg | png | rar | zip | js) ${valid_referers none blocked * .linuxidc.com*.linuxidc.net localhost 208.97.167.194 If ($invalid_referer) {rewrite ^ / https://cache.yisu.com/upload/information/20200622/115/46533.gif; return 412; break;} access_log off;root / opt/lampp/htdocs/web;expires 3D switch break;}
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.html
Rewrite ^ / 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
For example, / 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
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 is / area/shanghia/list_1.html will become / list_1.html, leading to inaccessible.
So it's not good for me to add automatic jump.
(- d $request_filename) it has a condition that it must be a real directory, but my rewrite is not, so it has no effect.
If (- d $request_filename) {rewrite ^ / (. *) ([^ /]) $http://$host/$1$2/permanent;}
It will be easy when I know the reason. Let me jump manually.
Rewrite ^ / ([0-9a-z] +) job$ / $1jobUniverse 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;}
6. Nginx global variable
The variable arg_PARAMETER # 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. The corresponding relationship between Apache and Nginx rules
RewriteCond of Apache corresponds to if of Nginx
RewriteRule of Apache corresponds to rewrite of Nginx
[r] of Apache corresponds to redirect of Nginx
[P] of Apache corresponds to last of Nginx
[Rmael] of Apache corresponds to redirect of Nginx.
[Apache] corresponds to Nginx's last.
[PT,L] of Apache corresponds to last of Nginx
For example, the specified domain name is allowed to access this site, and all other domain names are transferred to www.jb51.net.
Apache:
RewriteCond% {HTTP_HOST}! ^ (. *?)\ .aaa\ .com $[NC] RewriteCond% {HTTP_HOST}! ^ localhost$ RewriteCond% {HTTP_HOST}! ^ 192\ .168\ .0\. (. *?) $RewriteRule ^ / (. *) $/ / www.jb51.net [RMagol]
Example of Nginx filtering:
If ($host ~ * ^ (. *)\ .aaa\ .com $) {set $allowHost '1customers;} if ($host ~ * ^ localhost) {set $allowHost' 1cards;} if ($host ~ * ^ 192\ .168\ .1\. (. *?) $) {set $allowHost '1cards;} if ($allowHost! ~' 1') {rewrite ^ / (. *) $/ / www.jb51.netredirect } this is the end of the article on "implementation of forwarding matching rules in Nginx". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.