Examples of Nginx Rewrite rules with instructions and tips
- 2020-05-07 20:57:21
- OfStack
1. Regular expression matching, where:
* ~ matches for case sensitivity
* ~* is case-insensitive
*! ~ and! ~* are case - sensitive mismatches and case - insensitive mismatches, respectively
2. File and directory match, where:
* - f and! -f is used to determine if a file exists
* - d and! -d is used to determine if a directory exists
* - e and! -e is used to determine whether a file or directory exists
* - x and! -x is used to determine whether a file is executable
3. The last parameter of the rewrite instruction is the flag marker, and the flag marker is:
1.last is equivalent to the [L] tag in apache, indicating rewrite.
2. After the match of break rule is completed, the match is terminated and the subsequent rule is no longer matched.
3.redirect returns a 302 temporary redirect, and the browser address displays the URL address after the jump.
4.permanent returns a 301 permanent redirect, and the browser address displays the URL address after the jump.
URI rewrite using last and break, with the browser address bar unchanged. And there is a slight difference between the two, the use of alias instruction must be marked with last; When using the proxy_pass directive, the break flag is required. After the Last tag completes the execution of this rewrite rule, the server{... } the tag re-initiates the request, and the break tag terminates the match after the rule match is completed.
For example: if we will be similar to URL/photo / 123456 redirect to/path/to/photo / 12/1234/123456. png
rewrite "/photo/([0-9]{2})([0-9]{2})([0-9]{2})"/path/to/photo/$1/$1$2/$1$2$3.png ;
4. NginxRewrite rule related instruction
1. break instructions
Operating environment: server,location,if;
This directive completes the current rule set and no longer processes the rewrite directive.
2. if instructions
Environment: server,location
This directive is used to check whether a condition is met, and if it is, the statement in braces is executed. The If directive does not support nesting, and does not support multiple conditions && and || processing.
3. return instructions
Grammar: returncode;
Use environment: server,location,if;
This instruction is used to terminate the execution of the rule and return a status code to the client.
Example: if the URL being accessed ends in ".sh "or".bash ", a 403 status code is returned
location ~ .*\.(sh|bash)?$
{
return 403;
}
4. rewrite instructions
Syntax: rewriteregex replacement flag
Environment: server,location,if
This directive redirects URI based on the expression, or modifies the string. The instructions are executed according to the order in the configuration file. Note that the rewrite expression is only valid for relative paths. If you want to match hostnames, you should use the if statement, for example:
if( $host ~* www\.(.*) )
{
set $host_without_www $1;
rewrite ^(.*)$ http://$host_without_www$1permanent;
}
5. Set instructions
Grammar: setvariable value; Default value: none; Operating environment: server,location,if;
This directive is used to define a variable and assign a value to it. The value of a variable can be a combination of text, variables, and text variables.
Example: set$varname "hello world";
6. Uninitialized_variable_warn instructions
Grammar: uninitialized_variable_warnon | off
Using the environment: http, server location, if
This directive is used to turn on and off warning messages for uninitialized variables. The default value is on.
5. Rewrite rule writing instance of Nginx
1. Redirect to an php file when the files and directories accessed do not exist
if( !-e $request_filename )
{
rewrite ^/(.*)$ index.php last;
}
2. Directory swap /123456/xxxx ==== > /xxxx?id=123456
rewrite ^/(\d+)/(.+)/ /$2?id=$1 last;
3. If the client is using the IE browser, redirect to the /ie directory
if( $http_user_agent ~ MSIE)
{
rewrite ^(.*)$ /ie/$1 break;
}
4. Multiple directories are not accessible
location ~ ^/(cron|templates)/
{
deny all;
break;
}
5. Disallow access to files starting with /data
location ~ ^/data
{
deny all;
}
6. No access to. sh,. flv,. mp3 file suffix
location ~ .*\.(sh|flv|mp3)$
{
return 403;
}
7. Sets the browser cache time for certain types of files
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
{
expires 30d;
}
location ~ .*\.(js|css)$
{
expires 1h;
}
8. Set expiration time for favicon.ico and robots.txt;
favicon.ico for 99 days, robots.txt for 7 days, no 404 error logs
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; This is 600 seconds and no access logs are kept
location ^~ /html/scripts/loadhead_1.js {
access_log off;
root /opt/lampp/htdocs/web;
expires 600;
break;
}
10. File anti-hotlinking and set expiration time
return412 here is a custom http status code, default is 403, easy to find the correct hotlinking request
"rewrite ^ / http: / / img ofstack. com/leech gif;" Display 1 hotlinking - proof picture
"access_log off;" Do not log access to reduce stress
expires 3d 3-day browser cache of all files
location ~*^.+\.(jpg|jpeg|gif|png|swf|rar|zip|css|js)$ {
valid_referers none blocked *.ofstack.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;
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;
Convert files in multiple directories into one file to enhance the seo effect
/ job - 123-456-789. html point/job / 123/456/789. html
rewrite^/job-([0-9]+)-([0-9]+)-([0-9]+)\.html$ /job/$1/$2/jobshow_$3.html last;
13. Redirection when files and directories do not exist:
if (!-e $request_filename) {
proxy_pass http://127.0.0.1;
}
14. Point a folder in the root directory to a level 2 directory
Such as /shanghaijob/ point to /area/shanghai/
If you change last to permanent, the browser's address bar is /location/shanghai/
rewrite ^/([0-9a-z]+)job/(.*)$ /area/$1/$2last;
The problem with the above example is that it will not match when accessing /shanghai
rewrite ^/([0-9a-z]+)job$ /area/$1/ last;
rewrite ^/([0-9a-z]+)job/(.*)$ /area/$1/$2last;
So /shanghai is also accessible, but the relative links in the page are not available,
For example./ list_1.html the real address is /area/shanghia/ list_1.html will become/list_1.html, and cannot be accessed.
Then I also can't add automatic jump
(-d $request_filename) it has a condition that it must be a real directory, and my rewrite is not, so it has no effect
if (-d $request_filename){
rewrite ^/(.*)([^/])$ http://$host/$1$2/permanent;
}
It's easy to do after you know the reason, let me jump manually
rewrite ^/([0-9a-z]+)job$ /$1job/permanent;
rewrite ^/([0-9a-z]+)job/(.*)$ /area/$1/$2last;
15. Domain name jump
location ~ .*\.(sh|bash)?$
{
return 403;
}
8
16. Multi-domain redirection
location ~ .*\.(sh|bash)?$
{
return 403;
}
9
6. nginx global variable
arg_PARAMETER # this variable contains the value of the GET request if there is a variable PARAMETER.
args # is equal to the arguments in the request line (GET request), such as foo=123&bar=blahblah;
binary_remote_addr #2 base customer address.
The number of body bytes sent in response to body_bytes_sent #. This data is accurate even if the connection is broken.
content_length # request header Content-length field.
content_type # request header Content-Type field.
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 the server name.
hostname #Set to themachine's hostname as returned by gethostname
http_HEADER
If is_args # has an args parameter, this variable is equal to "?" , otherwise is equal to "", null value.
http_user_agent # client agent information
http_cookie # client cookie information
The variable limit_rate # limits the connection rate.
query_string # is the same as args.
request_body_file # client requests the temporary file name of the principal information.
The request_method # client requests an action, usually GET or POST.
remote_addr # client IP address.
remote_port # client port.
remote_user # has been authenticated by Auth Basic Module.
request_completion # if the request ends, set to OK. Null when the request does not end or if the request is not the last one in the request chain (Empty).
request_method # GET or POST
request_filename # the file path of the current request is generated by the root or alias instruction and URI request.
request_uri # contains the original URI of the request parameter, not the hostname, such as "/foo/ bar.php ? arg = baz ". It cannot be modified.
scheme #HTTP method (e.g. http, https).
server_protocol # requests the use of the protocol, usually HTTP/1.0 or HTTP/1.1.
server_addr # server address, which can be determined after one system call.
server_name # server name.
server_port # request arrives at the port number of the server.
7. Correspondence 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
The [P] of Apache corresponds to last of Nginx
The [R,L] of Apache corresponds to redirect of Nginx
The [P,L] of Apache corresponds to last of Nginx
The [PT,L] of Apache corresponds to last of Nginx
For example, allow the specified domain name to visit this site, other domain name 1 law to www.linuxidc.net
Apache:
if( $host ~* www\.(.*) )
{
set $host_without_www $1;
rewrite ^(.*)$ http://$host_without_www$1permanent;
}
0
Nginx:
if( $host ~* ^(.*)\.aaa\.com$ )
{
set $allowHost ' 1';
}
if( $host ~* ^localhost )
{
set $allowHost ' 1';
}
if( $host ~* ^192\.168\.1\.(.*?)$ )
{
set $allowHost ' 1';
}
if( $allowHost !~ ' 1' )
{
rewrite ^/(.*)$ http://www.linuxidc.netredirect ;
}
Rewrite rules are used in a number of places, but they are organized here so that you can look them up when you use them later.