Nginx Rewrite rule implementation tutorial and example

Source: Internet
Author: User
Tags php file regular expression browser cache


Syntax

Nginx Rewrite is much easier to understand than Apache. The main instructions include if, rewrite, set, return, and break. rewrite is the most critical command.

Rewrite

The code is as follows: Copy code
Syntax: rewrite regex replacement [flag];
Default value :-
Context: server, location, if



If the specified regular expression can match the URI, the URI will be rewritten by the string defined by the replacement parameter. The rewrite command is executed in the order it appears in the configuration file. Flag can terminate subsequent command execution. If the replacement string starts with "http: //" or "https: //", nginx ends the execution and returns a redirection to the client.
The optional flag parameter can be one of the following:
Last
Stop executing the ngx_http_rewrite_module instruction set for the current round, and search for the new location of the URI after matching and changing;
Break
Stop executing the ngx_http_rewrite_module instruction set of the current round;
Redirect
When the replacement string does not start with "http: //" or "https: //", use a temporary redirect with a return code of 302;
Permanent
Returns a permanent redirect with a status code of 301.
Example

The code is as follows: Copy code

Server {
...
Rewrite ^ (/download/. *)/media/(. *) .. * $1/mp3/listen 2.mp3 last;
Rewrite ^ (/download/. *)/audio/(. *) .. * $1/mp3/$ 2.ra last;
Return 403;
...
}



However, when the preceding commands are written in the "/download/" location, use the flag break instead of last. Otherwise, nginx will repeat 10 cycles, then error 500 is returned (for the difference between break and last, see break ):

The code is as follows: Copy code

Location/download /{
Rewrite ^ (/download/. *)/media/(. *) .. * $1/mp3/ipv2.mp3 break;
Rewrite ^ (/download/. *)/audio/(. *) .. * $1/mp3/$ 2.ra break;
Return 403;
}


If the replacement string contains new request parameters, the previous request parameters are added after the new parameters. If you do not want this, add a question mark "?" at the end of the replacement string. This can be avoided, for example:

The code is as follows: Copy code
Rewrite ^/users/(. *) $/show? User = $1? Last;



If the regular expression contains the character "}" or ";", the entire expression should be included in single quotes or double quotes.
Break

The code is as follows: Copy code
Syntax: break;
Default value :-
Context: server, location, if



Stop processing the current ngx_http_rewrite_module instruction set. For example:

The code is as follows: Copy code

If ($ slow ){
Limit_rate 10 k;
Break;
}



The implementation of last and break tags is similar, but there are slight differences between the two.When using the alias command, the last tag must be used. When using the proxy_pass command, the break tag must be used. After this rewrite rule is executed, the last mark will be applied to its server {...} the tag re-initiates the request, while the break tag terminates the match after the rule is matched. Therefore, it is generally in the root location (I .e. location /{...}) or write rewrite rules directly in the server tag. We recommend that you use the last tag. In non-location (such as location/cms /{...}), use the break flag.
For curly braces ({and}), they can be used both in the redirection regular expression and in the configuration file to separate code blocks. To avoid conflicts, if the regular expression contains curly brackets, it should be enclosed by double quotation marks (or single quotation marks), such as redirecting/photos/123456 to:/path/to/photos/12/1234/123456.png

The code is as follows: Copy code
Rewrite "/photos/([0-9] {2}) ([0-9] {2}) ([0-9] {2 }) "/path/to/photos/$1 $2/1_11_21_3.png>



If

The code is as follows: Copy code

Syntax: if (condition ){...}
Default value :-
Context: server, location



Used to check the condition. If it is true, execute the rewrite module instruction defined in braces. The if command does not support nesting and does not support multiple conditions & |.
The condition can be any of the following:
Variable name. If the variable value is null or a string starting with "0", the condition is false;
Use "=" and "! = "Operator compares variables and strings;
Use "~" (Case sensitive) and "~ * "(Case insensitive) operator matches variables and regular expressions. Regular expressions can contain matching groups. The variable $1 .. $9 can be referenced later in the matching result. If the regular expression contains the character "}" or ";", the entire expression should be included in single quotes or double quotes.
Use "-f" and "! -F "operator checks whether a file exists;
Use "-d" and "! -D "operator to check whether the directory exists;
Use "-e" and "! -E "operator checks whether a file, directory, or symbolic link exists;
Use "-x" and "! -X "operator checks executable files;
For example:

The code is as follows: Copy code

If ($ http_user_agent ~ MSIE ){
Rewrite ^ (. *) $/msie/$1 break;
}

If ($ http_cookie ~ * "Id = ([^;] + )(? :; | $ )"){
Set $ id $1;
}

If ($ request_method = POST ){
Return 405;
}

If ($ slow ){
Limit_rate 10 k;
}

If ($ invalid_referer ){
Return 403;
}


Set

The code is as follows: Copy code

Syntax: set variable value;
Default value :-
Context: server, location, if



Set the variable value for the specified variable. Value can contain text, variables, or their combinations. For example, see the following.

 


Rewrite_log

The code is as follows: Copy code

Syntax: rewrite_log on | off;
Default value:
Rewrite_log off;
Context: http, server, location, if



Enable or disable the processing log of the ngx_http_rewrite_module command and record it to the error log at the notice level.

 


Uninitialized_variable_warn

The code is as follows: Copy code

Syntax: uninitialized_variable_warn on | off;
Default value:
Uninitialized_variable_warn on;
Context: http, server, location, if



Controls whether to record warnings of variable uninitialized to logs.

 


Return

The code is as follows: Copy code

Syntax: return code [text];
Return code URL;
Return URL;
Default value :-
Context: server, location, if



Stop processing and return the specified code to the client. Status codes can use the following values: 204, 400, 402-406, 408, 410, 411, 413, and 416-500. In addition, the non-standard status code 444 ends the link without sending any Header.

Global variables used by nginx

The code is as follows: Copy code
$ Arg_PARAMETER # this variable contains the value in the GET request if the variable PARAMETER exists.
$ Args # This variable is equal to the parameters in the request line (GET request), for example, foo = 123 & bar = blahblah;
$ Binary_remote_addr # Binary Client address.
$ Body_bytes_sent # Number of body bytes sent when the response is sent. This data is accurate even if the connection is interrupted.
$ Content_length # Content-length field in the request header.
$ Content_type # Content-Type field in the request header.
$ Cookie_COOKIE # cookie variable value
$ Document_root # the value specified by the current request in the root command.
$ Document_uri # is the same as $ uri.
$ Host # Request host header field. Otherwise, it is the server name.
$ Hostname # Set to the machine's hostname as returned by gethostname
$ Http_HEADER
$ Is_args # if the $ args parameter exists, this variable is equal "?", Otherwise, it is equal to "" and null.
$ Http_user_agent # client agent information
$ Http_cookie # client cookie information
$ Limit_rate # this variable can limit the connection rate.
$ Query_string # is the same as $ args.
$ Request_body_file # temporary file name of the client request body information.
$ Request_method # The action requested by the client, usually GET or POST.
$ Remote_addr # IP address of the client.
$ Remote_port # The client port.
$ Remote_user # Username verified by Auth Basic Module.
$ Request_completion # if the request ends, it is set to OK. When the request is not completed or if the request is not the last of the request chain string, it is Empty (Empty ).
$ Request_method # GET or POST
$ Request_filename # the file path of the current request, which is generated by the root or alias command and URI request.
$ Request_uri # The original URI containing the request parameters, excluding the host name, for example, "/foo/bar. php? Arg = baz ". It cannot be modified.
$ Scheme # HTTP methods (such as http and https ).
$ Server_protocol # the protocol used by the request, usually HTTP/1.0 or HTTP/1.1.
$ Server_addr # server address, which can be determined after a system call.
$ Server_name # server name.
$ Server_port # the port number of the request to the server.
$ Uri # The current URI without the request parameters. $ uri does not contain the host name, for example, "/foo/bar.html ". This value may be inconsistent with $ request_uri. $ Request_uri is the value sent by the browser. This value is the value after rewrite. For example, after internal redirects is implemented.



Rewrite rule instance

When the Accessed file and directory do not exist, redirect to a php file

The code is as follows: Copy code

If (! -E $ request_filename ){
Rewrite ^/(. *) $ index. php last;
}



Directory swap/123456/xxxx ==>/ xxxx? Id = 123456

The code is as follows: Copy code

Rewrite ^/(d +)/(. +) // $2? Id = $1 last;



If the client uses the ie browser, redirect to the/ie directory.

The code is as follows: Copy code

If ($ http_user_agent ~ MSIE ){
Rewrite ^ (. *) $/ie/$1 break;
}


Prohibit access to multiple directories

The code is as follows: Copy code

Location ~ ^/(Cron | templates )/{
Deny all;
Break;
}


Prohibit access to files starting with/data

The code is as follows: Copy code

Location ~ ^/Data {
Deny all;
}



Prohibit objects whose names are .sh,.flv and suffix

The code is as follows: Copy code

Location ~ . *. (Sh | flv | mp3) $ {
Return 403;
}



Set the browser cache Time for some types of files

The code is as follows: Copy code

Location ~ . *. (Gif | jpg | jpeg | png | bmp | swf) $ {
Expires 30d;
}
Location ~ . *. (Js | css) $ {
Expires 1 h;
}



Comparison between Nginx and Apache Rewrite rule instances

Generally, simple Nginx rules are slightly different from Apache rules and are fully compatible. For example:

The code is as follows: Copy code

# Apache
RewriteRule ^/abc/$/web/abc. php [L]
# Nginx
Rewrite ^/abc/$/web/abc. php last;



We can see that you only need to change Apache RewriteRule to Nginx rewrite, and Apache [L] to last.
If you change Apache rules to Nginx rules and run the Nginx-t command to check for errors, you can try to quote the conditions. For example:

The code is as follows: Copy code

Rewrite "^/(%0-9%5%%%%.html $"/x. php? Id = $1 last;



The Rewrite rules of Apache and Nginx are slightly different in URL redirection:

The code is as follows: Copy code

# Apache
RewriteRule ^/html/([a-zA-Z] +)/. * $/$1/[R = 301, L]
# Nginx
Rewrite ^/html/([a-zA-Z] +)/. * $ http: // $ host/$1/premanent;



We can see that http: // $ host needs to be added in the Nginx jump, which is strongly required in Nginx.
The following describes the ing between Apache and Nginx rules.
Apache RewriteCond corresponds to Nginx if
Apache RewriteRule corresponds to Nginx rewrite
Apache [R] corresponds to Nginx redirect
Apache [P] corresponds to Nginx's last
Apache [R, L] corresponds to Nginx redirect
Apache's [P, L] corresponds to Nginx's last
Apache's [PT, L] corresponds to Nginx's last
For example, to allow a specified domain name to access this site, all other domain names are directed to www.xiaozhe.com Apache:

The code is as follows: Copy code

RewriteCond % {HTTP_HOST }! ^ (.*?). Aaa.com $ [NC]
RewriteCond % {HTTP_HOST }! ^ Localhost $
RewriteCond % {HTTP_HOST }! ^ 192.168.0 .(.*?) $
RewriteRule ^/(. *) $ http://www.xiaozhe.com [R, L]



Nginx:

The code is as follows: Copy code

If ($ host ~ * ^ (. *) .Aaa.com $)
{
Set $ allowHost '1 ';
}
If ($ host ~ * ^ Localhost)
{
Set $ allowHost '1 ';
}
If ($ host ~ * ^ 192.168.1 .(.*?) $)
{
Set $ allowHost '1 ';
}
If ($ allowHost !~ '1 ')
{
Rewrite ^/(. *) $ http://www.xiaozhe.com redirect;
}

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.