Examples of rewrite rule sources under Nginx: Linux Community

Source: Internet
Author: User
Tags browser cache

A Regular expression matching, where:
* ~ For case-sensitive matching
* ~* for case-insensitive matching
*!~ and!~* are case insensitive and case insensitive
Two File and directory matching, where:
*-F and!-f to determine if a file exists
*-D and!-d to determine if a directory exists
*-E and!-e to determine if a file or directory exists
*-X and!-x to determine if the file is executable
Three The last parameter of the rewrite directive is the flag flag, and the flag flag is:
1.last is equivalent to the [L] mark inside Apache, indicating rewrite.
2.break after the rule match is complete, the match is terminated and the subsequent rules are no longer matched.
3.redirect returns 302 temporary redirection, and the browser address displays the URL after the jump.
4.permanent returns 301 permanent redirection, and the browser address displays 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 between the two, using the alias directive must be marked with the last tag; use the break flag when using the PROXY_PASS directive. Last tag after the rewrite rule in this article has been executed, it will be server{...} The label re-initiates the request, and the break flag terminates the match after the rule match is complete.
For example, if we redirect a 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;


Four Nginxrewrite rules related directives


1.break instruction
Use environment: server,location,if;
The purpose of this directive is to complete the current set of rules and no longer process rewrite instructions.


2.if instruction
Usage Environment: server,location
The directive is used to check whether a condition is compliant, and if the condition conforms, the statement inside the curly braces is executed. If directives do not support nesting, multiple conditions are not supported && and | | Processing.


3.return instruction
Syntax: ReturnCode;
Use environment: server,location,if;
This instruction 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 visited ends with ". Sh" or ". Bash"
Location ~. *\. (Sh|bash)? $
{
return 403;
}


4.rewrite instruction
Syntax: Rewriteregex replacement flag
Usage Environment: SERVER,LOCATION,IF
The directive redirects the URI based on an expression, or modifies the string. Directives are executed according to the order in the configuration file. Note that the rewrite expression is valid only for relative paths. If you want to pair the hostname, you should use the IF statement, as in the following example:
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 the 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 directive
Syntax: Uninitialized_variable_warnon|off
Usage Environment: HTTP,SERVER,LOCATION,IF
This directive is used to open and close warning messages for uninitialized variables, and the default value is on.


Five An example of Nginx's rewrite rule writing
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. Catalogue 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. Disable access to multiple directories
Location ~ ^/(cron|templates)/
{
Deny all;
Break
}


5. Disable access to files beginning with/data
Location ~ ^/data
{
Deny all;
}


6. Prohibit access to files with. Sh,.flv,.mp3 as the 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 is favicon.ico for 99 days, robots.txt for 7 days does not log 404 error logs
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, do not log access logs
Location ^~/html/scripts/loadhead_1.js {
Access_log off;
Root/opt/lampp/htdocs/web;
Expires 600;
Break
}


10. File anti-hotlinking and set expiration time
The return412 here is a custom HTTP status code with a default of 403, which makes it easy to find the correct hotlinking request.
"Rewrite ^/http://img.linuxidc.net/leech.gif;" Show a picture of the anti-theft chain
"Access_log off;" Reduce stress by not logging access logs
"Expires 3d" All files 3-day browser cache


Location ~*^.+\. (JPG|JPEG|GIF|PNG|SWF|RAR|ZIP|CSS|JS) $ {
Valid_referers none blocked *.linuxidc.com*.linuxidc.net localhost 208.97.167.194;
if ($invalid _referer) {
Rewrite ^/http://img.linuxidc.net/leech.gif;
return 412;
Break
}
Access_log off;
Root/opt/lampp/htdocs/web;
Expires 3d;
Break
}


11. Allow only fixed IP access to the site, plus a 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 Convert files in multi-level directory into one file, enhance SEO effect
/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. Redirects when files and directories do not exist:


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


14. Point a folder under the root directory to a level 2 directory
such as/shanghaijob/point to/area/shanghai/
If you change last to permanent, then the browser address bar is/location/shanghai/
Rewrite ^/([0-9a-z]+) job/(. *) $/area/$1/$2last;
One of the problems with the above example is that access to/shanghai will not match
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,
If the real address of the./list_1.html is/area/shanghia/list_1.html will become/list_1.html, which leads to inaccessible.
Well, I'm not going to add the auto 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 after the good, let me manually jump
Rewrite ^/([0-9a-z]+) job$/$1job/permanent;
Rewrite ^/([0-9a-z]+) job/(. *) $/area/$1/$2last;


15. Domain Jump
Server
{
Listen 80;
server_name jump.linuxidc.com;
Index index.html index.htm index.php;
root/opt/lampp/htdocs/www;
Rewrite ^/http://www.linuxidc.com/;
Access_log off;
}


16. Multi-Domain Steering
server_name www.linuxidc.comwww.linuxidc.net;
Index index.html index.htm index.php;
Root/opt/lampp/htdocs;
if ($host ~ "Linuxidc\.net") {
Rewrite ^ (. *) http://www.linuxidc.com$1permanent;
}


Six Nginx Global Variables
Arg_parameter #这个变量包含GET请求中 If there is a value when the variable PARAMETER.
Args #这个变量等于请求行中 (GET request) parameters, such as:foo=123&bar=blahblah;
Binary_remote_addr #二进制的客户地址.
Body_bytes_sent #响应时送出的body字节数数量. Even if the connection is interrupted, the data is accurate.
Content_length #请求头中的Content the-length field.
Content_Type #请求头中的Content the-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 get or post.
REMOTE_ADDR #客户端的IP地址.
Remote_port #客户端的端口.
Remote_user #已经经过Auth the user name validated by the Basic module.
Request_completion #如果请求结束, set to OK. Empty when the request is not closed or if the request is not the last of the request chain string.
Request_method #GET或POST
Request_filename #当前请求的文件路径, generated by a root or alias instruction with a URI request.
Request_uri #包含请求参数的原始URI, does not contain a hostname, such as: "/foo/bar.php?arg=baz". Cannot be modified.
Scheme #HTTP方法 (e.g. Http,https).
Server_protocol #请求使用的协议, usually http/1.0 or http/1.1.
Server_addr #服务器地址, this value can be determined after a system call is completed.
server_name #服务器名称.
Server_port #请求到达服务器的端口号.


Seven The correspondence between Apache and Nginx rules
Apache's Rewritecond corresponds to Nginx if
Apache's rewriterule corresponds to Nginx's rewrite
Apache [R] corresponds to Nginx's redirect
Apache's [P] corresponds to the last of Nginx
Apache's [r,l] corresponds to Nginx's redirect
Apache's [p,l] corresponds to Nginx's last
Apache's [pt,l] corresponds to Nginx's last


For example: Allow the designated domain name to access the site, the other domain names are turned to Www.linuxidc.net
Apache:
Rewritecond%{http_host}!^ (. *?) \.AAA\.COM$[NC]
Rewritecond%{http_host}!^localhost$
Rewritecond%{http_host}!^192\.168\.0\. (.*?) $
Rewriterule ^/(. *) $ http://www.linuxidc.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.linuxidc.netredirect;
}

Recommended Reading :

The configuration and optimization of the reverse proxy and load balancing for Nginx http://www.linuxidc.com/Linux/2013-11/92909.htm

Nginx Load Balancer Report: Nginx: [Emerg] could not build the Types_hash http://www.linuxidc.com/Linux/2013-10/92063.htm

Nginx Load Balancer module Ngx_http_upstream_module details http://www.linuxidc.com/Linux/2013-10/91907.htm

Nginx+firebug lets the browser tell you which server the load balancer will send requests to http://www.linuxidc.com/Linux/2013-10/91824.htm

Ubuntu installation Nginx php5-fpm MySQL (LNMP environment Setup) http://www.linuxidc.com/Linux/2012-10/72458.htm

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.