{{ cat }}'s docs

26.6.0: NGINX配置-重定向&防盗链


0. rewrite理论

1) 官方文档解释

Syntax:        rewrite regex replacement [flag];  
Default:        -  
Context:        server, location, if

2) [flag]

3) 用在"if () {}"中

Syntax:        if (condition) { ... }
Default:        -
Context:        server, location
条件对象:变量、文件、目录;
操作符号:
=、!=         是否等于;
~、!~        是否匹配;
~*、!~*       是否匹配(忽略大小写);
-f、!-f       文件是否存在;
-d、!-d       目录是否存在;
-e、!-e       文件或目录是否存在;
-x、!-x       是否拥有执行权限
ps:如果条件单独为一变量,当此变量为空或者为0时,就为假

1. rewrite例子演示

## if判断语句+rewrite写法
# vim /usr/local/nginx/conf/vhost/test.conf
**********************************************
if ( $host != 'www.301r.com' ){
       rewrite ^/(.*)$ http://www.301r.com/$1 permanent;
}
**********************************************
# nginx -t
# nginx -s reload

# curl -x localhost:80 www.test.com/test -I
HTTP/1.1 301 Moved Permanently
Server: nginx/1.8.0
Date: Thu, 23 Jun 2016 17:21:30 GMT
Content-Type: text/html
Content-Length: 184
Connection: keep-alive
Location: www.baidu.com/test

## location+rewrite写法
# vim /usr/local/nginx/conf/vhost/test.conf
**********************************************
    location / {
        rewrite "/(.*)" www.baidu.com/$1 permanent;
        auth_basic      "Auth";
        auth_basic_user_file /usr/local/nginx/conf/.htpasswd;
    }
**********************************************
# nginx -t
# nginx -s reload
# curl -x localhost:80 www.test.com/test -I
HTTP/1.1 301 Moved Permanently
Server: nginx/1.8.0
Date: Thu, 23 Jun 2016 17:26:16 GMT
Content-Type: text/html
Content-Length: 184
Connection: keep-alive
Location: www.baidu.com/test

2. 防盗链

location ~* ^.+\.(gif|jpe?g|png|bmp|swf|rar|zip|flv|xls|bz2|gz|doc)$
    {
        valid_referers none blocked server_names *.google.com *.google.cn *.baidu.com;
        if ($invalid_referer)
        {
            return 403;
        }
    }
## 只允许google和baidu的refer访问特定格式文件

## 官方阅读:http://nginx.org/en/docs/http/ngx_http_referer_module.html

Contents