The rewrite module (ngx_HTTP_rewrite_module) is the default installation of Nginx. The rewrite module would rewrite urIs based on PCRE re matches, then initiate internal jumps to match locations, or do 30X redirects directly back to the client.

Order of instruction

  1. The rewrite module directives in the server block are executed sequentially to get the request URIs behind rewrite
  2. The loop then executes at most 10 times if no break flag is encountered, but we can use the break command to break the rewrite cycle

(1). Match the defined location block according to the rewrite request URI

(2). Execute the rewrite module directives in the matching location sequentially

instruction

break

Context: server, location, if

Stop executing the ngx_HTTP_rewrite_module directive set, but other module directives are not affected by the example illustration

server { listen 8080; # if you comment it out, all requests will return ok break; return 200 "ok"; location = /testbreak { break; return 200 $request_uri; Proxy_pass http://127.0.0.1:8080/other; } location / { return 200 $request_uri; }} # curl 127.0.0.1:8080/testbreak # /other If (proxy_pass is the ngx_HTTP_proxy_module directive) if (proxy_pass is the ngx_HTTP_proxy_module directive) if (proxy_pass is the ngx_HTTP_proxy_module directiveCopy the code

Context: server, location

Determines whether to execute the contents of the if block based on the specified condition

Several judgment conditions in if

  1. aThe variable nameFalse if the value of $variable is an empty string or string “0”
  2. variableComparison with a string equal to (=) not equal to (! =)Be careful not to use equality as an assignment statement here
  3. variableThe pattern matching operator for a regular expression can be (~Case-sensitive regular matching,~ *Case-insensitive regular matching,! ~! ~ *, the first two are not)
  4. Check whether the file is in use-fAnd! -f(Does not exist)
  5. Check whether the path is in use-dAnd! -dCan be a string or a variable
  6. Checks if a file, path, or link file is in use-eAnd! -eCan be a string or a variable
  7. Checks whether the file is used as an executable-x(Executable) and! -x(not executable) can be a string or a variable

4, 5, 6, and 7 can be variables or strings. -f/-d/-e/-x is the same as bash.

set $variable "0"; If ($variable) {# will not execute because "0" is false break; } # if ($http_host ~ "^star\.igrow\.cn$") {break; } # if ("star" ~ "^star\.igrow\.cn$") {break; } # check the string and variable of the file class if (! -f "/data.log" ) { break; } if ( ! -f $filename ) { break; }Copy the code

return

Context: server, location, if

return code [text];
return code URL;
return URL;
Copy the code

Stops processing and returns the specified code to the client. Non-standard code 444 closes a connection without sending a response header.

Starting with version 0.8.42, return statements can specify the redirected URL (the status code can be 301,302, 302, 307) or the text content of the response for other status codes, and the redirected URL and the text of the response can contain variables.

There is a special case where the redirected URL can be specified as a urI local to the server. In this case, nginx will use the requested protocol $scheme, Server_name_in_redirect and port_IN_redirect generate complete urls automatically The directive specifies whether to redirect the server_name and listen ports from the server block.

# return code [text]; Return ok to client location = /ok {return 200 "ok"; } # return code URL; Redirect {return 302 http://www.baidu.com; } # return URL; Location = /redirect {return http://www.baidu.com; }Copy the code

rewrite

Context: server, location, if

rewrite regex replacement [flag];
Copy the code

The rewrite directive uses the specified regular expression regex to match the urI of the request and, if the match is successful, uses replacement to change the urI. The rewrite directives are executed in the order they appear in the configuration file. A flag can be used to terminate further processing of the instruction. If the replacement string replacement begins with http://, https://, or $scheme, the subsequent content is stopped and redirected back to the client.

The first case rewrites the string with http://

Location / {# request will be temporarily redirected to http://www.$1.com when matching regular expression /test1/(.*) # http://www.$1.com; return 200 "ok"; #} in the browser input 127.0.0.1:8080 / test1 / baidu temporary redirect to www.baidu.com # # is the back of the return instruction there will be no chance to performCopy the code

The second case rewrites the string without http://

location / { rewrite /test1/(.*) www.$1.com; return 200 "ok"; } # requests the following # curl 127.0.0.1:8080 / test1 / baidu # # ok here without http:// so simply rewrite. /test1/baidu: /test1/baidu: www.baidu.com # rewrite: /test1/baidu: www.baidu.com #Copy the code

Rewrite’s four flags

  1. Last stops processing the current ngx_HTTP_rewrite_module directive set and starts searching for locations that match the changed URI; (Because last in English means “continue “, will continue to try to match jump to other location)

  2. Break stops processing the current ngx_HTTP_rewrite_module directive set, just like the break directive above; (break is stop)

  3. Redirect Returns 302 temporary redirect. (Understood as “temporary rental “)

  4. Permanent Returns a 301 permanent redirection. (Move to a new house)

    Do this sequentially without rewriting followed by any flag

    Rewrite to initiate a new location match when no rewrite module directive can be executed in a location

    Rewrite ^/test1 /test2. rewrite ^/test2 /test3; /test3}

    location = /test2 { return 200 “/test2”; }

    location = /test3 { return 200 “/test3”; }

    Send the following request

    The curl 127.0.0.1:8080 / test1

    /test3

The difference between last and break

Last, like break, terminates execution of any other of its rewrite module directives in this location, but last immediately initiates a new location match while break does not

location / { rewrite ^/test1 /test2; rewrite ^/test2 /test3 last; Rewrite ^/test3 /test4; proxy_pass http://www.baidu.com; } location = /test2 { return 200 "/test2"; } location = /test3 { return 200 "/test3"; } location = /test4 { return 200 "/test4"; Rewrite ^/test1 / rewrite ^/test1 / rewrite ^/test1 / rewrite ^/ test2; # no new location match will be initiated; Rewrite ^/test2 /more/index.html break; rewrite ^/test2 /more/index.html break rewrite /more/index\.html /test4; # because proxy_pass is not a rewrite module directive it cannot be terminated by break proxy_pass https://www.baidu.com; } # # to send the following request browser input 127.0.0.1: # 8080 / test1 agent to baidu product page https://www.baidu.com/more/index.html;Copy the code

Request parameters after rewrite

If the replacement string replacement contains new request parameters, the previous request parameters are appended after them. If you don’t want the previous arguments, place a question mark at the end of the replacement string replacement to avoid attaching them.

# Because of the last? Rewrite ^/users/(.*)$/show? user=$1? last;Copy the code

rewrite_log

Context: http, server, location, if

Turn on or off logging of the rewrite module directives. If this is enabled, rewriting will write notice level logs to nginx’s error_log (off by default)

Syntax: rewrite_log on | off;
Copy the code

set

Context: server, location, if

Sets the value of the specified variable. The value of a variable can contain text, variables, or a combination of them.

location / { set $var1 "host is "; set $var2 $host; set $var3 " uri is $request_uri"; return 200 "response ok $var1$var2$var3"; } # curl 127.0.0.1:8080/test # response OK host is 127.0.0.1 URI is /testCopy the code

uninitialized_variable_warn

Context: http, server, location, if

Controls whether warnings about uninitialized variables are logged. The default open

Internal implementation

The ngx_HTTP_rewrite_module module directive interprets internal instructions during configuration phase compilation into requested processing. The interpreter is a simple virtual stack machine.

For example, instructions

location /download/ { if (
f o r b i d d e n ) r e t u r n 403 ; i f ( forbidden) { return 403; } if (
slow) { limit_rate 10k; } rewrite ^/(download/.*)/media/(.*)\.. *
/ /
1/mp3/$2.mp3 break; }

Will be translated into the following description:

variable
f o r b i d d e n c h e c k a g a i n s t z e r o r e t u r n 403 e n d o f c o d e v a r i a b l e forbidden check against zero return 403 end of code variable
slow check against zero match of regular expression copy “/” copy
1 c o p y / m p 3 / c o p y 1 copy “/mp3/” copy
2 copy “.mp3” end of regular expression end of code

Note that the limit_rate directive above does not have any directives because it has nothing to do with the ngx_HTTP_rewrite_module module. Create a separate configuration for the if block. If the condition is true, a request is assigned for this configuration with limit_rate equal to 10K.

instruction

rewrite ^/(download/.*)/media/(.*)\.. *
/ /
1/mp3/$2.mp3 break;

If the first slash in a regular expression is enclosed in parentheses, it can be simplified:

rewrite ^(**/**download/.*)/media/(.*)\.. *
1/mp3/$2.mp3 break;

The corresponding instruction will look like this:

match of regular expression copy
1 c o p y / m p 3 / c o p y 1 copy “/mp3/” copy
2 copy “.mp3” end of regular expression end of code

Location (non-rewrite module)

grammar

Used in server blocks, for example:

  • server {
  • Location expression {
  • }
  • }

Location expression type

  • If you write a path directly, the path under the path matches
  • ~ indicates that a regular match is performed, which is case sensitive
  • ~* indicates that a regular match is performed, case insensitive
  • ^~ indicates a common character match. Use prefix matching. If the match is successful, no more locations will be matched.
  • = Perform normal character exact matching. So it’s a perfect match.

priority

  1. The equal sign type (=) has the highest priority. Once a match is successful, no more matches are looked for.
  2. ^~ Type expression. Once a match is successful, no more matches are looked for.
  3. The priority of the regular expression type (~ ~*). If more than one location regex matches, the one with the longest regular expression is used.
  4. General string matching type. Match by prefix.

I hope the above content can help you. Many PHPer will encounter some problems and bottlenecks when they are advanced, and they have no sense of direction when writing too many business codes. I have sorted out some information, including but not limited to: Distributed architecture, high scalability, high performance, high concurrency, server performance tuning, TP6, Laravel, Redis, Swoft, Kafka, Mysql optimization, shell scripting, Docker, microservices, Nginx, etc. Many knowledge points can be free to share with you