Refer to the redirection configuration guide in the Nginx server

  • 2020-05-10 23:32:38
  • OfStack

rewrite command
rewrite of nginx is equivalent to rewriterule of apache (in most cases you can use rewrite of apache in quotation marks). It can be used in server,location and IF conditional judgment blocks. The format of the command is as follows:
The rewrite regular expression replaces the target flag token
The flag markup can be used in the following formats:

last basically USES this Flag. The break wok has aborted Rewirte and is no longer matching The redirect wok returns the temporary redirected HTTP status 302 The permanent wok returns permanent redirected HTTP status 301

For example, the following paragraph sets nginx to redirect files under a directory to another directory,$2 corresponds to the string in the second parenthesis (.*) :


location /download/ {
rewrite ^(/download/.*)/m/(.*)\..*$ $1/nginx-rewrite/$2.gz break;
}

nginx redirects IF conditional judgment
The IF conditions of nginx can be used in server and location situations. The conditions can be as follows:
1. Regular expressions
Match judgment
~   for case-sensitive matching; ! ~ does not match for case sensitivity
  ~* for case-insensitive matching; ! ~ does not match for case insensitivity
For example, set nginx to redirect users using ie to the/nginx-ie directory:


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

2. File and directory judgment
  (1) -f and! -f determines if a file exists
  (2) -d and! -d determines if a directory exists
  (3) -e and! -e determines if a file or directory exists
  (4) -x and! -x determines whether the file is executable
For example, here's how to set nginx to redirect when files and directories don't exist:


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

3.return
Return the http code, such as setting nginx anti-hotlinking:


location ~* \.(gif|jpg|png|swf|flv)$ {
valid_referers none blocked www.jefflei.com www.leizhenfang.com;
if ($invalid_referer) {
return 404;
}
}

4. set:
Set the nginx variable

301 redirect code
A 301 redirection, such as merging www.ofstack.com with ofstack.com, and merging the previous domain name with ofstack.com, can be done in two ways. The first method is to determine the nginx core variable host(the old version was http_host) :


server {
server_name www.ofstack.com ofstack.com ;
if ($host != 'www.ofstack.com' ) {
rewrite ^/(.*)$ //www.ofstack.com/$1 permanent;
}
...
}

Method 2:


server {
server_name ofstack.com;
rewrite ^/(.*)$ //www.ofstack.com/$1 permanent;
}

The first method, ok, was tested. Of the two methods, permanent is the key. See the nginx redirection rule specification for details.

The last works mostly with this Flag. The break wok terminates Rewirte and no longer matches The redirect wok returns the temporary redirected HTTP status 302 The permanent wok returns the permanent redirected HTTP state 301

Related articles: