Nginx redirection rules
Nginx redirection uses the HttpRewriteModule of Nginx. The following describes how to use it:
Rewrite command
Nginx rewrite is equivalent to apache rewriterule (in most cases, the original apache rewrite rules can be directly used with quotation marks). It can be used in server, location, and IF condition judgment blocks, the command format is as follows:
Replace the target flag with the rewrite Regular Expression
The flag can be in the following formats:
Last-this Flag is basically used.
Break-Abort Rewirte and do not continue matching
Redirect-return the HTTP status 302 of the temporary redirect
Permanent-returns the HTTP status 301 for permanent redirection
For example, the following section sets nginx to redirect the files under a directory to another directory. $2 corresponds to the corresponding string in the second bracket:
location /download/ {
rewrite ^(/download/.*)/m/(.*)\..*$ $1/nginx-rewrite/$2.gz break;
}
IF condition judgment for nginx redirection
The IF condition of nginx can be used to determine the server and location. The conditions can be as follows:
Regular Expression
For example:
Matching and judgment
~ It is case-sensitive ;!~ Case-insensitive
~ * Case-insensitive match ;!~ Case-insensitive
For example, set nginx to redirect to the/nginx-ie directory when you use ie:
if ($http_user_agent ~ MSIE) {
rewrite ^(.*)$ /nginx-ie/$1 break;
}
File and directory judgment
-F and! -F indicates whether a file exists.
-D and! -D: determines whether a directory exists.
-E and! -E: Determine whether a file or directory exists.
-X and! -X determines whether the file is executable.
For example, set nginx to redirect when the file and directory do not exist:
if (!-e $request_filename) {
proxy_pass http://127.0.0.1;
}
ReturnReturn the http Code, for example, setting nginx anti-leech:
Location ~ * \. (Gif | jpg | png | swf | flv) $ {
Valid_referers none blocked www.jefflei.com www.leizhenfang.com;
If ($ invalid_referer ){
Return 404;
}
}
SetSet nginx Variables