Nginx rewrite rules and usage introduction and techniques examples _nginx

Source: Internet
Author: User
Tags browser cache

A Regular expression matches, where:

* ~ to Match case sensitivity
* ~* matching for case-insensitive case
*!~ and!~* are case insensitive and case-insensitive mismatches, respectively

Two File and directory matching, where:

*-F and!-f are used to determine whether a file exists
*-D and!-d used to determine whether a directory exists
*-E and!-e used to determine whether a file or directory exists
*-X and!-x are used to determine whether a file is executable

Three The last parameter of the rewrite instruction is the flag tag, and the 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.
For example, if we redirect similar url/photo/123456 to/path/to/photo/12/1234/123456.png

Copy Code code as follows:

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

Four Nginxrewrite rules related directives

1.break instruction

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

Usage 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.

3.return instruction

Grammar: ReturnCode;
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"

Copy Code code as follows:

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

4.rewrite instruction

Syntax: Rewriteregex replacement flag
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:

Copy Code code as follows:

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

5.Set instruction

Syntax: SetVariable 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_warnon|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.

Five Nginx Rewrite Rule Writing example

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

Copy Code code as follows:

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

2. Directory Swap/123456/xxxx ====>/xxxx?id=123456
Copy Code code as follows:

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

3. If the client is using IE browser, redirect to the/ie directory
Copy Code code as follows:

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

4. Prohibit access to multiple directories
Copy Code code as follows:

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

5. Prohibit access to documents beginning with/data
Copy Code code as follows:

Location ~ ^/data
{
Deny all;
}

6. Prohibit access to files with a. sh,.flv,.mp3 file suffix name
Copy Code code as follows:

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

7. Set browser cache time for certain types of files
Copy Code code as follows:

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
Copy Code code as follows:

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
Copy Code code as follows:

Location ^~/html/scripts/loadhead_1.js {
Access_log off;
Root/opt/lampp/htdocs/web;
Expires 600;
Break
}

10. File hotlinking and set expiration time

Here the return412 is a custom HTTP status code, the default is 403, to easily find the right hotlinking request
"Rewrite ^/http://img.jb51.net/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

Copy Code code as follows:

Location ~*^.+\. (JPG|JPEG|GIF|PNG|SWF|RAR|ZIP|CSS|JS) $ {
Valid_referers none blocked *.jb51.net*.linuxidc.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 Web site, plus password

Copy Code code as follows:

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

Copy Code code as follows:

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

13. redirect When files and directories do not exist:
Copy Code code as follows:

if (!-e $request _filename) {
Proxy_pass http://127.0.0.1;
}

14. 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/$2last;
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/$2last;
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

Copy Code code as follows:

if (-D $request _filename) {
Rewrite ^/(. *) ([^/]) $ http://$host/$1$2/permanent;
}

Know the reason to do it, let me manually jump it
Copy Code code as follows:

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

15. Domain Name jump
Copy Code code as follows:

Server
{
Listen 80;
server_name jump.jb51.net;
Index index.html index.htm index.php;
root/opt/lampp/htdocs/www;
Rewrite ^/http://www.jb51.net/;
Access_log off;
}

16. Multi-Domain Change
Copy Code code as follows:

server_name www.jb51.net www.jb51.net;
Index index.html index.htm index.php;
Root/opt/lampp/htdocs;
if ($host ~ "Linuxidc\.net") {
Rewrite ^ (. *) http://www.jb51.net$1permanent;
}

Six. Nginx Global Variables

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相同.
Host #请求主机头字段, otherwise the server name.
Hostname #Set to Themachine ' s hostname as returned by GetHostName
Http_header
Is_args #如果有args参数, this variable equals "?", otherwise equals "", null value.
Http_user_agent #客户端agent信息
Http_cookie #客户端cookie信息
Limit_rate #这个变量可以限制连接速率.
Query_string #与args相同.
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 #请求到达服务器的端口号.

Seven The correspondence between Apache and Nginx rules

The rewritecond of Apache corresponds to the Nginx if
The rewriterule of Apache corresponds to the rewrite of Nginx.
Apache's [R] corresponds to Nginx's redirect
The [P] of Apache corresponds to the last of the Nginx
The [r,l] of Apache corresponds to the Nginx redirect
Apache's [p,l] corresponds to the Nginx's last
Apache's [pt,l] corresponds to the Nginx's last

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

Copy Code code as follows:

Rewritecond%{http_host}!^ (. *?) \.AAA\.COM$[NC]
Rewritecond%{http_host}!^localhost$
Rewritecond%{http_host}!^192\.168\.0\. (.*?) $
Rewriterule ^/(. *) $ http://www.jb51.net[r,l]

Nginx:

Copy Code code as follows:

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.linuxidc.netredirect;
}

Rewrite rules are used in many places, sorted here, easy to use when you are ready to find.

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.