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
- The rewrite module directives in the server block are executed sequentially to get the request URIs behind rewrite
- 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
- a
The variable name
False if the value of $variable is an empty string or string “0” variable
Comparison with a string equal to (=) not equal to (! =)Be careful not to use equality as an assignment statement here
variable
The pattern matching operator for a regular expression can be (~
Case-sensitive regular matching,~ *
Case-insensitive regular matching,! ~! ~ *
, the first two are not)- Check whether the file is in use
-f
And! -f
(Does not exist) - Check whether the path is in use
-d
And! -d
Can be a string or a variable - Checks if a file, path, or link file is in use
-e
And! -e
Can be a string or a variable - 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
-
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)
-
Break stops processing the current ngx_HTTP_rewrite_module directive set, just like the break directive above; (break is stop)
-
Redirect Returns 302 temporary redirect. (Understood as “temporary rental “)
-
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 (
slow) { limit_rate 10k; } rewrite ^/(download/.*)/media/(.*)\.. *
1/mp3/$2.mp3 break; }
Will be translated into the following description:
variable
slow check against zero match of regular expression copy “/” 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
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
- The equal sign type (=) has the highest priority. Once a match is successful, no more matches are looked for.
- ^~ Type expression. Once a match is successful, no more matches are looked for.
- The priority of the regular expression type (~ ~*). If more than one location regex matches, the one with the longest regular expression is used.
- 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