Detail the commonly used nginx rewrite rewrite rule

  • 2020-05-17 07:39:26
  • OfStack

This article provides some common rewrite rewriting rules to beautify web links. The $1, $2 in the rule if you don't know where it comes from, just remember, the first () is the $1, and the second () is the $2.

The requested URL is for people to see, and the rewritten URL is for computers to see.

Perform a search

The purpose of this rule is to perform a search for the keywords contained in URL.

Request URL / / hqidi com search/some search -- keywords
Rewritten URL / / hqidi com/search php & # 63; p = some search -- keywords
Rewrite rule rewrite ^/search/(.*)$/ search. php? p = $1 & # 63;;

User profile page

Most dynamic web sites that run visitor signup provide a page where you can view your profile. The URL of this page contains the user's UID and user name

Request URL / / hqidi com/user / 47 / dige
Rewritten URL / / hqidi com/user php & # 63; id = 47 & name = dige
Rewrite rules rewrite ^ / user/([0-9] +)/(. +) $/ user php & # 63; id = $1 & name = $2 & # 63;;

Multiple parameters

Some sites use a different syntax for string parameters, such as separating unnamed parameters by a slash of "/"

Request URL / / hqidi com/index php/param1 / param2 / param3
Rewritten URL / / hqidi com/index php & # 63; p1 = param1 & p2 = param2 & p3 = param3
Rewrite rules rewrite ^ / index php/(. *)/(. *)/(. *) $/ index php & # 63; p1 = $1 & p2 = $2 & p3 = $3 & # 63;;

Similar to the encyclopedia format

This format features a 1-prefix directory followed by the article name

Request URL / / hqidi com/wiki/some - keywords
Rewritten URL / / hqidi com/wiki/index php & # 63; title = some - keywords
Rewrite rule rewrite ^/wiki/(.*)$/wiki/ index. php? title = $1 & # 63;;

BBS

Forum 1 generally USES two parameters, 1 topic id (topic) and 1 starting point (starting post).

Request URL / / hqidi com/topic - 1234-50 - some - keywords. html
Rewritten URL / / hqidi com/viewtopic php & # 63; topic = 1234 & start = 50
Rewrite rules rewrite ^ / topic - ([0-9] +) - ([0-9] +) - (. *) \. html $viewtopic. php & # 63; topic = $1 & start = $2 & # 63;;

Articles for the new website

This URL structure features an article identifier, followed by a slash, and a list of keywords.

Request URL / / hqidi com / 88 / future
Rewritten URL / / hqidi com/atricle php & # 63; id = 88
Rewrite rule rewrite ^/([0-9]+)/.*$/ aticle.php ? id = $1 & # 63;;

The last question mark

If the replaced URI contains parameters (such as /app/ test.php ? id=5 or something like URI), the parameter is automatically appended to the replacement string by default, by adding ? to the end of the replacement string; Tag to solve this 1 problem.

rewrite ^/users/(.*)$ /show?user=$1? last;

Compare one plus? Marked and unmarked? Marked URL jump distinction:

rewrite ^/test(.*)$ //hqidi.com/home premanent;

Access / / hqidi com/test & # 63; id = 5 after 301 jump URL address for/with / / hqidi com/home & # 63; id = 5

rewrite ^/test(.*)$ //hqidi.com/home? premanent;

Access / / hqidi com/test & # 63; id = 5 after 301 jump URL address for/with / / hqidi com/home

The rewrite function of Nginx requires the support of PCRE software, that is, rule matching through perl compatible regular expression statements. Compiling nginx by default will support the rewrite module, but PCRE support is also required

rewrite is the key instruction to achieve URL rewrite. According to part of regex (regular expression), redirect to replacement, ending with the flag tag.

nginx rewrite instruction execution order

1. Execute the rewrite instruction of server block (the block here refers to the area surrounded by {} after the server keyword; other xx blocks are similar)
2. Perform location matching
3. Execute the rewrite instruction in the selected location

If one of these steps URI is overwritten, loop through 1-3 until the real file is found.

If the loop exceeds 10 times, 500 Internal Server Error error is returned.

flag flags

The syntax of rewrite is simple, such as:


rewrite regex URL [flag];

rewrite is the keyword, regex is the regular expression, URL is the content to be replaced, [flag] is the token bit meaning, it has the following values:

last: the [L] flag equivalent to Apache, indicating completion of rewrite break: stops executing the subsequent rewrite instruction set of the current virtual host redirect: return 302 temporary redirection, the address bar will show the address after the jump permanent: return 301 permanent redirect, the address bar will show the address after the jump

Since 301 and 302 cannot simply return status codes, they must also have redirected URL, which is why the return directive cannot return 301,302. The difference between last and break is a bit confusing here:

last1 is written in server and if, while break1 is used in location last does not terminate the url match after the rewrite, that is, the new url will go through the matching process again from server, while break terminates the match after the rewrite Both break and last are able to organize the continuation of the rewrite instructions

Consider a simple example:


rewrite ^/listings/(.*)$ /listing.html?listing=$1 last;
rewrite ^/images/(.*)_(\d+)x(\d+)\.(png|jpg|gif)$ /resizer/$1.$4?width=$2&height=$3? last;

Article 1 to rewrite the rules, we can use a friendly URL: http: / / mysite com/listings / 123 instead of http: / / mysite com/listing html & # 63; listing = 123, as we enter in the browser's address bar http: / / mysite com/listings / 123, after the actual access URL resource is http: / / mysite com/listing html & # 63; listing = 123.

In rule 2, to form such as http: / / mysite com/images/bla_500x400 jpg file request, rewrite the http: / / mysite com/resizer/bla jpg & # 63; width=500&height=400 addresses and will continue to try to match location.

if directive with global variables

if instruction syntax is if(condition){... }, for the given condition condition. If true, the rewrite instruction in curly braces will be executed.

Look at the code rules:


if ($http_user_agent ~ MSIE) {
  rewrite ^(.*)$ /msie/$1 break;
} // if UA contains "MSIE" . rewrite Request to the /msid/ directory 
 
if ($http_cookie ~* "id=([^;]+)(?:;|$)") {
  set $id $1;
 } // if cookie Match the regular, set the variable $id Is equal to the regular reference part 
 
if ($request_method = POST) {
  return 405;
} // If the submit method is POST , returns the status 405 ( Method not allowed ). return Can't return 301,302
 
if ($slow) {
  limit_rate 10k;
} // The speed limit, $slow Can be achieved by  set  Instruction set 
 
if (!-f $request_filename){
  break;
  proxy_pass http://127.0.0.1; 
} // If the requested file name does not exist, reverse proxy to localhost  . Here, break Also stop rewrite check 
 
if ($args ~ post=140){
  rewrite ^ http://mysite.com/ permanent;
} // if query string Contained in the "post=140" , redirect permanently to mysite.com

In the if directive, you can use global variables, such as:

$args: # is equal to the argument in the request line, the same as $query_string $content_length: the Content-length field in the request header. $content_type: the Content-Type field in the request header. $document_root: the value currently requested in the root directive. $host: request the host header field, otherwise the server name. $http_user_agent: client agent information$http_cookie: client cookie information $limit_rate: this variable limits the connection rate. $request_method: the action requested by the client, usually GET or POST. $remote_addr: the IP address of the client. $remote_port: client port. $remote_user: username that has been authenticated by Auth Basic Module. $request_filename: the file path for the current request, generated by the root or alias instructions and the URI request. $scheme: HTTP agreement (e.g. http, https). $server_protocol: the protocol requested, 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 server's port number. $request_uri: the original URI containing the request parameters, not the hostname, as in "/foo/ bar.php ? arg = baz ". $uri: current URI without request parameters, $uri without host name, such as "/foo/ bar.html". $document_uri: same as $uri.

Jump using return

Sometimes we need to use rewrite on Nginx to do 301 address jumps, such as the following rules:


rewrite ^ $scheme://www.mysite.com$request_uri permanent;

When accessing any url, 301 is permanently directed to www.mysite.com's url. This is correct, but because the regular matching of rewrite is used, 1 part of the resource will be lost, which is not recommended on the nginx website. We can also use return to achieve a 301 jump, simple and practical, see an example:

301 is permanently directed to the new domain name


server {
  listen 80;
  listen 443 ssl;
  server_name www.old-name.com old-name.com;
  return 301 $scheme://www.new-name.com;
}

The above code to achieve the old domain 301 jump to the new domain name, if the site to change the new domain name to use this method to do 301 jump.

A 301 without www jumps to a domain with www


server {
  listen 80;
  listen 443 ssl;
  server_name mysite.com;
  return 301 $scheme://www.mysite.com$request_uri;
}

The http site 301 jumps to the https site


server {
  listen 80;
  server_name www.mysite.com;
  return 301 https://www.mysite.com$request_uri;
}

Related articles: