Nginx rewrite rules How to configure?

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

In the process of URL optimization, it is unavoidable to involve nginx rewrite rules. So how is the Nginx rewrite configured?
Rewrite can be found in 4 places: ngx_http_srv_conf,ngx_http_sif_conf,ngx_http_loc_conf,ngx_http_lif_conf. correspond to each other:

Ngx_http_srv_conf: Anywhere in the server domain in the configuration file;
Ngx_http_sif_conf: In the If configuration in the server domain in the configuration file;
Ngx_http_loc_conf: Anywhere in the location domain in the configuration file;
Ngx_http_lif_conf: In the If configuration in the location domain in the configuration file;

Examples are as follows:

//...
server {
//...
Rewrite "^/+$"/index.php break;

if ($uri ~* "^/+abc") {
Rewrite "^/+ABC"/abc/index.php break;
}

Location/xy {
Rewrite "^/+xy$"/xy/index.php break;
}
}
?
1
The detailed description of location and the powerful features of location can be searched in the search box of this website by typing "ngingx location".

Add

1.break instruction

Default value: None; use environment: server,location,if;

The purpose of this instruction is to complete the current rule set and no longer process the rewrite instruction.

2.if instruction

Default value: none; Using environment: Server,location

The directive is used to check whether a condition is compliant and, if the condition is met, to execute the statement within the curly braces. If directive does not support nesting, multiple conditions are not supported && and | | Processing.

A. Variable name, the wrong value includes: empty string "" or any string starting with 0
B. Variable comparisons can use "=" (representing equals) and "!=" (means not equal to)
C. Regular expression pattern matching can use the "~*" and "~" symbols
D. " ~ "Symbol for matching case letters match
E. " ~* "notation for case-insensitive matching of uppercase and lowercase letters
F. "! ~ "and"!~* "the function of the symbol just and" ~ "," ~* "opposite, indicating mismatch
G. " -F "and"!-f "to determine whether a file exists
H. " -D "and"!-d "to determine if the directory exists
I. " -E "and"!-e "to determine whether a file or directory exists
J. " -X "and"!-x "to determine if the file is executable
K. Partial regular expressions can be accessed in (), with $1~$9
3.return instruction

Syntax: return code; Use environment: server,location,if;

This directive is used to end the execution of the rule and return the status code to the client.

Example: Returns a 403 status code if the URL that is accessed ends with ". Sh" or ". Bash"

Location ~. *. (Sh|bash)? $
{
return 403;
}
4.rewrite instruction

Syntax: Rewrite regex replacement flag

Default value: none; Usage Environment: SERVER,LOCATION,IF

The directive redirects the URI according to an expression, or modifies the string. Directives are executed according to the order in which they are in the configuration file. Note An overriding expression is only valid for a relative path. If you want to match the host name, you should use the IF statement, as follows:

if ($host ~* www. (. *) )
{
Set $host _without_www $;
Rewrite ^ (. *) $ http://$host _without_www$1 permanent;
}

The last parameter of the rewrite directive is a flag tag, and the support flag tag is:

1.last is equivalent to the [L] tag inside Apache, representing rewrite.

2.break After this rule is finished, the match is terminated and the following rule is no longer matched.

3.redirect returns 302 temporary redirection, and the browser address displays the URL address after the jump.

4.permanent Returns 301 Permanent Redirect, the browser address will display the URL address after the jump.

URI overrides are implemented using last and break, and the browser address bar does not change. And there is a slight difference, the alias directive must be marked with last, and the break tag is used when using the Proxy_pass directive. The last mark after the execution of the rewrite rule for this article will server{...} The label restarts the request, and the break tag terminates the match after this rule match completes.

Generally in with location (location/{...}) or write the rewrite rule directly in the Server tab, use the last tag, or break in the non-root location (location/cms/{...}).

If the URI contains a parameter (/app/test.php?id=5), the parameter is automatically appended to the replacement string by default, and you can resolve the problem by adding the tag at the end of the replacement string.

For example:

Rewrite ^/test (. *) $ http://www.111cn.net/home permanent;
Access Http://www.111cn.net/test?id=5 will jump to http://www.111cn.net/home?id=5

For example, if we redirect similar url/photo/123456 to/path/to/photo/12/1234/123456.png

Rewrite "/photo/([0-9]{2}) ([0-9]{2}) ([0-9]{2})"/path/to/photo/$1/$1$2/$1$2$3.png;

Note: If there are curly braces "{" or "}" inside the regular expression, you should use double quotes or single quotes.

5.Set instruction

Syntax: Set variable value; Default value: none; Use environment: server,location,if;

The directive is used to define a variable and assign a value to a variable. The value of a variable can be a union of text, variables, and text variables.

Example: Set $varname "Hello World";

6.uninitialized_variable_warn directives

Syntax: Uninitialized_variable_warn on|off

Usage Environment: HTTP,SERVER,LOCATION,IF

This directive is used to turn warning messages on and off for uninitialized variables, and the default value is on.

7.Nginx rewrite global variables that can be used

$args, $content _length, $content _type, $document _root, $document _uri, $host, $http _user_agent, $http _cookie, $limit _ Rate, $request _body_file, $request _method, $remote _addr, $remote _port, $remote _user, $request _filename, $request _uri, $query _string, $scheme, $server _protocol, $server _addr, $server _name, $server _port, $uri

(see appendix for details) = = = = = =

Nginx Rewrite Rule Writing example

1. Redirect to a php file when the file and directory you are accessing does not exist

if (!-e $request _filename)
{
Rewrite ^/(. *) $ index.php last;
}

2. Directory Swap/123456/xxxx ====>/xxxx?id=123456

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

3. If the client is using IE browser, redirect to the/ie directory

if ($http _user_agent ~ msie)
{
Rewrite ^ (. *) $/ie/$1 break;
}

4. Prohibit access to multiple directories

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

5. Prohibit access to documents beginning with/data

Location ~ ^/data
{
Deny all;
}

6. Prohibit access to files with a. sh,.flv,.mp3 file suffix name

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

7. Set browser cache time for certain types of files

Location ~. *. (gif|jpg|jpeg|png|bmp|swf) $
{
Expires 30d;
}
Location ~. *. (JS|CSS) $
{
Expires 1h;
}
8. Set expiration time for Favicon.ico and robots.txt;
Here for Favicon.ico 99 days, robots.txt 7 days does not record 404 error log

Location ~ (favicon.ico) {





Log_not_found off;





Expires 99d;





Break





}











Location ~ (robots.txt) {





Log_not_found off;





Expires 7d;





Break





}


9. Set the expiration time of a file; This is 600 seconds, and the access log is not logged

Location ^~/html/scripts/loadhead_1.js {





Access_log off;





Root/opt/lampp/htdocs/web;





Expires 600;





Break





}


10. File hotlinking and set expiration time
The return 412 here is a custom HTTP status code, the default is 403, to easily find the right hotlinking request
"Rewrite ^/yun_qi_img/leech.gif;" Display an anti-theft chain picture
"Access_log off;" Do not log access logs to reduce stress
"Expires 3d" browser cache for all files 3 days

Location ~* ^.+. (JPG|JPEG|GIF|PNG|SWF|RAR|ZIP|CSS|JS) $ {





Valid_referers none blocked *.c1gstudio.com *.c1gstudio.net localhost 208.97.167.194;





if ($invalid _referer) {





Rewrite ^/yun_qi_img/leech.gif;





return 412;





Break





}





Access_log off;





Root/opt/lampp/htdocs/web;





Expires 3d;





Break





}


11. Only allow fixed IP access to the site, and add password

root/opt/htdocs/www;





Allow 208.97.167.194;





Allow 222.33.1.2;





Allow 231.152.49.4;





Deny all;





Auth_basic "C1g_admin";





Auth_basic_user_file htpasswd;


12 to the multi-level directory of files into a file, enhance the effect of SEO
/job-123-456-789.html Point to/job/123/456/789.html

Rewrite ^/job-([0-9]+)-([0-9]+)-([0-9]+). html$/job/$1/$2/jobshow_$3.html last;

13. Point a folder under the root directory to level 2 directory
such as/shanghaijob/point to/area/shanghai/
If you change the last to permanent, then the browser address bar is/location/shanghai/

Rewrite ^/([0-9a-z]+) job/(. *) $/area/$1/$2 last;

The problem with the example above is that it will not match when accessing the/shanghai

Rewrite ^/([0-9a-z]+) job$/area/$1/last;

Rewrite ^/([0-9a-z]+) job/(. *) $/area/$1/$2 last;

This/shanghai can also be accessed, but the relative links in the page are not available.
such as./list_1.html real address is/area/shanghia/list_1.html will become/list_1.html, lead to inaccessible.

Then I'll go with the automatic jump.
(-D $request _filename) It has a condition that is required for the real directory, and my rewrite is not, so no effect

if (-D $request _filename) {

Rewrite ^/(. *) ([^/]) $ http://$host/$1$2/permanent;

}

Know the reason to do it, let me manually jump it

Rewrite ^/([0-9a-z]+) job$/$1job/permanent;

Rewrite ^/([0-9a-z]+) job/(. *) $/area/$1/$2 last;

14. redirect When files and directories do not exist:

if (!-e $request _filename) {

Proxy_pass http://127.0.0.1;

}

Comparison of rewrite rule examples between Nginx and Apache

1. Generally simple nginx and Apache rules are not very different and can be completely compatible, for example:

Apache:rewriterule ^/abc/$/web/abc.php [L]

Nginx:rewrite ^/abc/$/web/abc.php last;

We can see that as long as the Apache Rewriterule changed to Nginx Rewrite,apache [L] instead of last.

If you change the Apache rule to a Nginx rule, and then use the command nginx-t check to find the error, we can try to enclose the condition in quotes, for example:

Rewrite "^/([0-9]{5}). html$"/x.php?id=$1 last;

The rewrite rules for 2.Apache and nginx have subtle differences in URL jumps:

Apache:rewriterule ^/html/([a-za-z]+)/.*$/$1/[r=301,l]

Nginx:rewrite ^/html/([a-za-z]+)/.*$ http://$host/$1/premanent;

We can see in the nginx jump, we need to add http://$host, which is strongly required in Nginx.

3. Here are the corresponding relationships between Apache and Nginx rules.

The A.apache rewritecond corresponds to the nginx if

The rewriterule of B.apache corresponds to Nginx rewrite

C.apache [R] corresponds to the Nginx redirect

D.apache [P] corresponds to the last of the Nginx

E.apache [r,l] corresponds to Nginx redirect

F.apache [p,l] corresponds to the last of Nginx

G.apache [pt,l] corresponds to the last of Nginx

For example: to allow the designated domain name access to the site, the other domain name all turn to Www.111cn.net

Apache:

Rewritecond%{http_host}!^ (. *?). aaa.com$ [NC]
Rewritecond%{http_host}!^localhost$
Rewritecond%{http_host}!^192.168.0. (.*?) $
Rewriterule ^/(. *) $ http://www.111cn.net [r,l]

Nginx:

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.111cn.net redirect;
}
Appendix: Nginx Global Variables

It is often necessary to configure Nginx, which has many variables beginning with $, and often needs to refer to variables supported by Nginx. Implementation of Nginx supported HTTP variables in NGX_HTTP_VARIABLES.C ngx_http_core_variables storage

Ngx_http_core_variables


Static ngx_http_variable_t ngx_http_core_variables[] = {





{ngx_string ("Http_host"), NULL, Ngx_http_variable_header,


Offsetof (ngx_http_request_t, Headers_in.host), 0, 0},





{ngx_string ("Http_user_agent"), NULL, Ngx_http_variable_header,


Offsetof (ngx_http_request_t, Headers_in.user_agent), 0, 0},





{ngx_string ("Http_referer"), NULL, Ngx_http_variable_header,


Offsetof (ngx_http_request_t, Headers_in.referer), 0, 0},





#if (Ngx_http_gzip)


{ngx_string ("Http_via"), NULL, Ngx_http_variable_header,


Offsetof (ngx_http_request_t, Headers_in.via), 0, 0},


#endif





#if (Ngx_http_proxy | | Ngx_http_realip)


{ngx_string ("http_x_forwarded_for"), NULL, Ngx_http_variable_header,


Offsetof (ngx_http_request_t, Headers_in.x_forwarded_for), 0, 0},


#endif





{ngx_string ("Http_cookie"), NULL, Ngx_http_variable_headers,


Offsetof (ngx_http_request_t, Headers_in.cookies), 0, 0},





{ngx_string ("content_length"), NULL, Ngx_http_variable_header,


Offsetof (ngx_http_request_t, Headers_in.content_length), 0, 0},





{ngx_string ("Content_Type"), NULL, Ngx_http_variable_header,


Offsetof (ngx_http_request_t, Headers_in.content_type), 0, 0},





{ngx_string ("host"), NULL, ngx_http_variable_host, 0, 0, 0},





{ngx_string ("binary_remote_addr"), NULL,


NGX_HTTP_VARIABLE_BINARY_REMOTE_ADDR, 0, 0, 0},





{ngx_string ("remote_addr"), NULL, ngx_http_variable_remote_addr, 0, 0, 0},





{ngx_string ("Remote_port"), NULL, Ngx_http_variable_remote_port, 0, 0, 0},





{ngx_string ("server_addr"), NULL, ngx_http_variable_server_addr, 0, 0, 0},





{ngx_string ("Server_port"), NULL, Ngx_http_variable_server_port, 0, 0, 0},





{ngx_string ("Server_protocol"), NULL, Ngx_http_variable_request,


Offsetof (ngx_http_request_t, Http_protocol), 0, 0},





{ngx_string ("scheme"), NULL, Ngx_http_variable_scheme, 0, 0, 0},





{ngx_string ("Request_uri"), NULL, Ngx_http_variable_request,


Offsetof (ngx_http_request_t, Unparsed_uri), 0, 0},





{ngx_string ("uri"), NULL, Ngx_http_variable_request,


Offsetof (ngx_http_request_t, Uri),


ngx_http_var_nocacheable, 0},





{ngx_string ("Document_uri"), NULL, Ngx_http_variable_request,


Offsetof (ngx_http_request_t, Uri),


ngx_http_var_nocacheable, 0},





{ngx_string ("request"), NULL, Ngx_http_variable_request_line, 0, 0, 0},





{ngx_string ("Document_root"), NULL,


Ngx_http_variable_document_root, 0, ngx_http_var_nocacheable, 0},





{ngx_string ("Realpath_root"), NULL,


Ngx_http_variable_realpath_root, 0, ngx_http_var_nocacheable, 0},





{ngx_string ("query_string"), NULL, Ngx_http_variable_request,


Offsetof (ngx_http_request_t, args),


ngx_http_var_nocacheable, 0},





{ngx_string ("args"),


Ngx_http_variable_request_set,


Ngx_http_variable_request,


Offsetof (ngx_http_request_t, args),


ngx_http_var_changeable| ngx_http_var_nocacheable, 0},





{ngx_string ("Is_args"), NULL, Ngx_http_variable_is_args,


0, ngx_http_var_nocacheable, 0},





{ngx_string ("Request_filename"), NULL,


Ngx_http_variable_request_filename, 0,


ngx_http_var_nocacheable, 0},





{ngx_string ("SERVER_NAME"), NULL, Ngx_http_variable_server_name, 0, 0, 0},





{ngx_string ("Request_method"), NULL,


Ngx_http_variable_request_method, 0,


ngx_http_var_nocacheable, 0},





{ngx_string ("Remote_user"), NULL, Ngx_http_variable_remote_user, 0, 0, 0},





{ngx_string ("body_bytes_sent"), NULL, Ngx_http_variable_body_bytes_sent,


0, 0, 0},





{ngx_string ("request_completion"), NULL,


Ngx_http_variable_request_completion,


0, 0, 0},





{ngx_string ("Request_body"), NULL,


Ngx_http_variable_request_body,


0, 0, 0},





{ngx_string ("Request_body_file"), NULL,


Ngx_http_variable_request_body_file,


0, 0, 0},





{ngx_string ("Sent_http_content_type"), NULL,


Ngx_http_variable_sent_content_type, 0, 0, 0},





{ngx_string ("Sent_http_content_length"), NULL,


Ngx_http_variable_sent_content_length, 0, 0, 0},





{ngx_string ("sent_http_location"), NULL,


Ngx_http_variable_sent_location, 0, 0, 0},





{ngx_string ("sent_http_last_modified"), NULL,


ngx_http_variable_sent_last_modified, 0, 0, 0},





{ngx_string ("sent_http_connection"), NULL,


Ngx_http_variable_sent_connection, 0, 0, 0},





{ngx_string ("sent_http_keep_alive"), NULL,


ngx_http_variable_sent_keep_alive, 0, 0, 0},





{ngx_string ("sent_http_transfer_encoding"), NULL,


ngx_http_variable_sent_transfer_encoding, 0, 0, 0},





{ngx_string ("Sent_http_cache_control"), NULL, Ngx_http_variable_headers,


Offsetof (ngx_http_request_t, Headers_out.cache_control), 0, 0},





{ngx_string ("limit_rate"), Ngx_http_variable_request_set_size,


Ngx_http_variable_request_get_size,


Offsetof (ngx_http_request_t, Limit_rate),


ngx_http_var_changeable| ngx_http_var_nocacheable, 0},





{ngx_string ("nginx_version"), NULL, Ngx_http_variable_nginx_version,


0, 0, 0},





{ngx_string ("hostname"), NULL, Ngx_http_variable_hostname,


0, 0, 0},





{ngx_string ("pid"), NULL, Ngx_http_variable_pid,


0, 0, 0},





{ngx_null_string, NULL, NULL, 0, 0, 0}


};


These variables are extracted and summarized as follows:

Arg_parameter #这个变量包含GET请求中, if there is a variable PARAMETER value.


Args #这个变量等于请求行中 (GET request) parameters, such as foo=123&bar=blahblah;


Binary_remote_addr #二进制的客户地址.


Body_bytes_sent #响应时送出的body字节数数量. This data is accurate even if the connection is interrupted.


Content_length #请求头中的Content-length field.


Content_Type #请求头中的Content-type field.


Cookie_cookie #cookie The value of a COOKIE variable


Document_root #当前请求在root指令中指定的值.


Document_uri #与


URI is the same.


Host #请求主机头字段, otherwise the server name.


Hostname #Set to the machine ' s hostname as returned by GetHostName


Http_header


Is_args #如果有


Args argument, this variable equals "?", otherwise equals "", null value.


Http_user_agent #客户端agent信息


Http_cookie #客户端cookie信息


Limit_rate #这个变量可以限制连接速率.


Query_string #与


Args the same.


Request_body_file #客户端请求主体信息的临时文件名.


Request_method #客户端请求的动作, usually a get or post.


REMOTE_ADDR #客户端的IP地址.


Remote_port #客户端的端口.


Remote_user #已经经过Auth the user name validated by Basic module.


Request_completion #如果请求结束, set to OK. NULL when the request is not closed or if the request is not the last of the request chain string (Empty).


Request_method #GET或POST


Request_filename #当前请求的文件路径, generated by root or alias directives and URI requests.


Request_uri #包含请求参数的原始URI, does not contain host names, such as "/foo/bar.php?arg=baz". Cannot be modified.


Scheme #HTTP方法 (such as Http,https).


Server_protocol #请求使用的协议, usually http/1.0 or http/1.1.


Server_addr #服务器地址, this value can be determined once the system call has been completed.


server_name #服务器名称.


Server_port #请求到达服务器的端口号.

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.