usage of nginx rewrite

Usage scenarios

  • Adjust the URL format for user browsing, so that it looks more standard
  • In order to let the search engine include the website content, get better user experience
  • Using a new domain to replace the old one
  • According to the special variables, directory, client information, jump to the specified configuration

rewrite syntax

Syntax: rewrite regex replacement [flag];
default: —
Context: server、location、if

Rewrite is an important instruction to implement URL redirection. It matches the content according to regex (regular expression), jumps to replacement, and ends with flag tag.

Common regular expressions

charactor description
\ Mark the following character as a special character or a literal character or a backward reference
^ Matches the starting position of the input string
$ Matches the end position of the input string
* Matches the preceding character zero or more times
+ Matches the previous string one or more times
? Matches the preceding string zero or once
. Match all single characters except ‘\ n’
(pattern) Match the pattern in brackets

The flag parameter of rewrite

flag description
last After this rule is matched, continue to match the new location URI rule downward
break This rule will be terminated after matching, and no rules will be matched
redirect Return to 302 temporary redirection
permanent Return to 301 permanent redirection

An example

rewrite ^/(.*) http://www.google.com/ permanent;     # After successful matching, it will jump to google and execute permanent 301 jump

原创文章,作者:ifee,如若转载,请注明出处:https://www.ifee.win/blog/2021/05/11/usage-of-nginx-rewrite/

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注