nginx rewrite rules Detailed

Rewrite Profile

rewrite function is to use a global variable or variables provided by nginx set up their own, combined with regular expressions and flags achieve url rewrite and redirect.
rewrite only on the server {}, location {}, if {} , and act only outside the string parameter passed behind the removed name.
Show look a bit like a rewrite function and location, can realize the jump, the main difference 在于rewrite是在同一域名内更改获取资源的路径,而location是对一类路径做控制访问或反向代理,可以proxy_pass到其机器。
rewrite many cases will be written in the location where their execution order:

Server execution block rewrite instruction
execution location matching
rewrite instruction in the selected execution location
if the step in which a URI is overwritten, then re-execute cycle 1-3 until you find the file actually exists; cycle more than 10 times, the process returns 500 Internal Server error error.

Flag flag

last: Apache corresponding to the [L] flag indicating the completion of the current rewrite rule
break: execute the subsequent rewrite a set of instructions to stop the current virtual host
redirect: Back 302 temporary redirection, the address jump address bar displays
permanent: 301 returns permanent redirection, address address bar will show a jump
because only return to reason and 302 status code, there must be redirected URL, which is the return instruction can not be simply unable to return to 301 and 302 of the 301.

last and break difference:
last generally written in the server and if in general use in the location and break the
last match does not terminate after url rewriting, that the new url will then move from server to match the process again, and break rewritten after termination match

if the global variable instruction

if the instruction is determined

Syntax if (condition) {...}, the given condition is found to be determined. If true, rewrite instructions within the braces will be executed, if the condition (conditon) may be any of the following elements:

1. When a variable expression only, if the value is null or false as any string that begins with 0 are 2
2. Direct comparison variables and content, or the use =! =
3 ~ regular expression matching, ~ * the case-insensitive matching,! ~ not case-sensitive match

-f和!-f用来判断是否存在文件
-d和!-d用来判断是否存在目录
-e和!-e用来判断是否存在文件或目录
-x和!-x用来判断文件是否可执行

if ($http_user_agent ~ MSIE) {
    rewrite ^(.*)$ /msie/$1 break;
} //如果UA包含"MSIE",rewrite请求到/msid/目录下
if ($http_cookie ~* "id=([^;]+)(?:;|$)") {
    set $id $1;
 } //如果cookie匹配正则,设置变量$id等于正则引用部分
if ($request_method = POST) {
    return 405;
} //如果提交方法为POST,则返回状态405(Method not allowed)。return不能返回301,302
if ($slow) {
    limit_rate 10k;
} //限速,$slow可以通过 set 指令设置
if (!-f $request_filename){
    break;
    proxy_pass  http://127.0.0.1; 
} //如果请求的文件名不存在,则反向代理到localhost 。这里的break也是停止rewrite检查
if ($args ~ post=140){
    rewrite ^ http://example.com/ permanent;
} //如果query string中包含"post=140",永久重定向到example.com
location ~* .(gif|jpg|png|swf|flv)$ {
    valid_referers none blocked www.jefflei.com www.leizhenfang.com;
    if ($invalid_referer) {
        return 404;
    } //防盗链
}

Global Variables

$args : #这个变量等于请求行中的参数,同$query 大专栏  nginx rewrite 规则详解_string

$content_length : 请求头中的Content-length字段。

$content_type : 请求头中的Content-Type字段。

$document_root : 当前请求在root指令中指定的值。

$host : 请求主机头字段,否则为服务器名称。

$http_user_agent : 客户端agent信息

$http_cookie : 客户端cookie信息

$limit_rate : 这个变量可以限制连接速率。

$request_method : 客户端请求的动作,通常为GET或POST。

$remote_addr : 客户端的IP地址。

$remote_port : 客户端的端口。

$remote_user : 已经经过Auth Basic Module验证的用户名。

$request_filename : 当前请求的文件路径,由root或alias指令与URI请求生成。

$scheme : HTTP方法(如http,https)。

$server_protocol : 请求使用的协议,通常是HTTP/1.0或HTTP/1.1。

$server_addr : 服务器地址,在完成一次系统调用后可以确定这个值。

$server_name : 服务器名称。

$server_port : 请求到达服务器的端口号。

$request_uri : 包含请求参数的原始URI,不包含主机名,如:”/foo/bar.php?arg=baz”。

$uri : 不带请求参数的当前URI,$uri不包含主机名,如”/foo/bar.html”。

$document_uri : 与$uri相同。


http://localhost:88/test1/test2/test.php
$host:localhost
$server_port:88
$request_uri:http://localhost:88/test1/test2/test.php
$document_uri:/test1/test2/test.php
$document_root:/var/www/html
$request_filename:/var/www/html/test1/test2/test.php

Common regular

.: Match any character other than a new line
?: Repeat 0 or 1
+: repeated one or more times
*: 0 or more times repeated
d: matching digits
^: start of the string matching
$: Introduction string matching
{n}: repeated n time
{n,}: repeated n times or more
[c]: matching a single character C
[a-z]: match any lowercase letters az a
small content match between parenthesis () can be produced by later reference to $ 1, $ 2 represents the second front () the contents. Regular people get confused which is the escape special characters.

http {
    # 定义image日志格式
    log_format imagelog '[$time_local] ' $image_file ' ' $image_type ' ' $body_bytes_sent ' ' $status;
    # 开启重写日志
    rewrite_log on;

    server {
        root /home/www;

        location / {
                # 重写规则信息
                error_log logs/rewrite.log notice; 
                # 注意这里要用‘’单引号引起来,避免{}
                rewrite '^/images/([a-z]{2})/([a-z0-9]{5})/(.*).(png|jpg|gif)$' /data?file=$3.$4;
                # 注意不能在上面这条规则后面加上“last”参数,否则下面的set指令不会执行
                set $image_file $3;
                set $image_type $4;
        }

        location /data {
                # 指定针对图片的日志格式,来分析图片类型和大小
                access_log logs/images.log mian;
                root /data/images;
                # 应用前面定义的变量。判断首先文件在不在,不在再判断目录在不在,如果还不在就跳转到最后一个url里
                try_files /$arg_file /image404.html;
        }
        location = /image404.html {
                # 图片不存在返回特定的信息
                return 404 "image not foundn";
        }
}

The shape of /images/ef/uh7b3/test.png request to rewrite /data?file=test.png, then matched to the location / data, look /data/images/test.png file exists or not, If there is a normal response, if there is a new rewriting tryfiles image404 location, status code 404 directly returns.

Guess you like

Origin www.cnblogs.com/liuzhongrong/p/11873914.html