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



0. rewrite理论

1) 官方文档解释

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

#### 2) [flag]
- last  
停止执行目前的ngx_http_rewrite_module指令,然后查找匹配改变后的URI的位置
- break  
仅停止执行目前的指令
- redirect  
在replacement字符串未以"http://"或"https://"开头时,使用返回状态码为302的临时重定向
- permanent   
返回状态码为301的永久重定向。

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

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

---

### 1. rewrite例子演示
``` bash
## 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