Rewrite rules under Nginx

one. Regular expression matching, where:
* ~ is case-sensitive matching
* ~* is case-insensitive matching
* !~ and !~* are case-sensitive mismatch and case-insensitive mismatch
II. File and directory matching, where:
* -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
three. The last parameter of the rewrite instruction is the flag flag. The flag flags are:
1.last is equivalent to the [L] flag in apache, which means rewrite.
2.break After the matching of this rule is completed, the matching is terminated, and the following rules are no longer matched.
3.redirect returns 302 temporary redirection, and the browser address will display the redirected URL address.
4.permanent returns 301 permanent redirection, and the browser address will display the redirected URL address.


Use last and break to implement URI rewriting, and the browser address bar remains unchanged. And there are subtle differences between the two. The alias directive must be marked with last; when the proxy_pass directive is used, the break mark must be used. The Last tag will re-request the server{...} tag where the rewrite rule is located after the execution of this rewrite rule, and the break tag will terminate the matching after the matching of this rule is completed.
For example: if we redirect a URL like /photo/123456 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 ;


Four. NginxRewrite rule related instructions


1. Use environment of the break instruction
: server, location, if;
the function of this instruction is to complete the current rule set and no longer process the rewrite instruction.


2. The if command
uses the environment: server, location
This command is used to check whether a condition is met, and if the condition is met, the statement in the curly brackets is executed. The If directive does not support nesting, and does not support multiple conditional && and || processing.


3. Return instruction
syntax: returncode;
usage 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", return 403 status code
location ~ .*\.(sh|bash)?$
{
return 403;
}


4. Rewrite command
syntax: rewriteregex replacement flag
Use environment: server, location, if
This command redirects the URI according to the expression, or modifies the string. Instructions are executed according to the order in the configuration file. Note that rewrite expressions are only valid for relative paths. If you want to pair hostnames, you should use an if statement, example:
if( $host ~* www\.(.*) )
{
set $host_without_www $1;
rewrite ^(.*)$ http://$host_without_www$1 permanent;
}


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 text, variables, and combinations of text variables.
Example: set$varname "hello world";


6. Uninitialized_variable_warn command
syntax: uninitialized_variable_warnon|off
Use environment: http, server, location, if
This command is used to turn on and off the warning information of uninitialized variables. The default value is on.

 


Fives. Nginx's Rewrite rule writing example
1. When the accessed file and directory do not exist, redirect to a php file
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 IE browser, redirect to /ie directory
if( $http_user_agent ~ MSIE)
{
rewrite ^(.*)$ /ie/$1 break;
}


4. Prohibit access to multiple directories
location ~ ^/(cron|templates)/
{
deny all;
break;
}


5. Forbid access to files starting with /data
location ~ ^/data
{
deny all;
}


6. Prohibit access to files with .sh, .flv, .mp3 file extensions
location ~ .*\.(sh|flv|mp3)$
{
return 403;
}


7. Set browser cache time for certain 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 is 99 days for favicon.ico, 7 days for robots.txt and does not record 404 error log
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 is 600 seconds, and access logs are not recorded
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
. The return412 here is a custom http status code, the default is 403, which is convenient to find the correct hotlinking request
"rewrite ^/ http://img.linuxidc.net/leech. gif;"Show a picture of anti-theft chain
"access_log off;"Do not record access logs, reduce stress
"expires 3d" Browser cache for all files for 3 days


location ~*^.+\.(jpg|jpeg|gif|png|swf|rar|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;
break;
}


11. Only allow fixed ip to access the website and add 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 the multi-level directory 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 in the root directory to the second-level directory
such as /shanghaijob/ points to /area/shanghai/
If you change last to permanent, then the browser address bar shows /location/shanghai/
rewrite ^/([0 -9a-z]+)job/(.*)$ /area/$1/$2last;
The 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 Can not be used,
such as ./list_1.html real address is /area/shanghia/list_1.html will become /list_1.html, resulting in inaccessible.
Then I 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;
} Once
you know the reason, it will be easy, let me jump manually
rewrite ^/([0-9a-z]+)job$ /$1job/permanent;
rewrite ^/([0-9a-z]+)job/(.*)$ /area/$1/$2last;


15.域名跳转
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.多域名转向
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;
}


six. nginx global variable
arg_PARAMETER #This variable contains the value of the variable PARAMETER in the GET request.
args #This variable is equal to the parameters in the request line (GET request), such as: foo=123&bar=blahblah;
binary_remote_addr #Binary client address.
body_bytes_sent #Number of body bytes sent in response. This data is accurate even if the connection is dropped.
content_length #Content-length field in the request header.
content_type #Content-Type field in the request header.
cookie_COOKIE #cookie COOKIE variable value
document_root #The value specified in the root directive for the current request.
document_uri #same as uri.
host #Request host header field, otherwise the server name.
hostname #Set to themachine's hostname as returned by gethostname
http_HEADER
is_args #If there is an args parameter, this variable is equal to "?", otherwise equal to "", null.
http_user_agent #Client agent information
http_cookie #Client cookie information
limit_rate #This variable can limit the connection rate.
query_string #same as args.
request_body_file #Temporary file name of client request body information.
request_method #The action requested by the client, usually GET or POST.
remote_addr #IP address of the client.
remote_port #The port of the client.
remote_user #The username that has been authenticated by the Auth Basic Module.
request_completion #If the request is completed, set to OK. When the request is not completed or if the request is not the last of the request chain, it is empty (Empty).
request_method #GET or POST request_filename #The
file path of the current request, generated by the root or alias directive and the URI request.
request_uri #Contains the original URI of the request parameters, excluding the hostname, such as: "/foo/bar.php?arg=baz". Can not be modified.
scheme #HTTP method (eg http, https).
server_protocol #The protocol used by the request, usually HTTP/1.0 or HTTP/1.1.
server_addr #Server address, this value can be determined after completing a system call.
server_name #Server name.
server_port #The port number of the request to the server.


seven. The correspondence between Apache and Nginx rules
Apache's RewriteCond corresponds to Nginx's if
Apache's RewriteRule corresponds to Nginx's rewrite
Apache's [R] corresponds to Nginx's redirect
Apache's [P] corresponds to Nginx's last
Apache's [R, L] corresponds to Nginx's redirect
Apache's [P, L] corresponds to Nginx's last
Apache's [PT, L] corresponds to Nginx's last


For example: Allow the specified domain name to access this site, and other domain names will be redirected 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]


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

Recommended reading :

 

Nginx realizes the configuration and optimization of reverse proxy and load balancinghttp ://www.linuxidc.com/Linux/2013-11/92909.htm

 

Nginx reports for load balancing: nginx: [emerg] could not build the types_hash http://www.linuxidc.com/Linux/2013-10/92063.htm

 

Nginx load balancing module ngx_http_upstream_module details http://www.linuxidc.com/Linux/2013-10/91907.htm

 

Nginx+Firebug lets the browser tell you which server the load balancer distributes the request to http://www.linuxidc.com/Linux/2013-10/91824.htm

 

Ubuntu installs Nginx php5-fpm MySQL (LNMP environment construction) http://www.linuxidc.com/Linux/2012-10/72458.htm

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326482768&siteId=291194637