配合配置實例對常用指令進行說明
## break
停止執行ngx_http_rewrite_module指令集模塊,不影響其他模塊。
```
server {
listen 8080;
# 此處 break 會停止執行 server 塊的 return 指令(return 指令屬于rewrite模塊)
# 如果把它注釋掉 則所有請求進來都返回 ok
break;
return 200 "ok";
location = /testbreak {
break;
return 200 $request_uri;
proxy_pass http://127.0.0.1:8080/other;
}
location / {
return 200 $request_uri;
}
}
# 發送請求如下
# curl 127.0.0.1:8080/testbreak
# /other
# 可以看到 返回 `/other` 而不是 `/testbreak`,說明 `proxy_pass` 指令還是被執行了
# 也就是說 其他模塊的指令是不會被 break 中斷執行的
# (proxy_pass是ngx_http_proxy_module的指令)
```
## if
```
set $variable "0";
if ($variable) {
# 不會執行,因為 "0" 為 false
break;
}
# 使用變量與正則表達式匹配 沒有問題
if ( $http_host ~ "^star\.igrow\.cn$" ) {
break;
}
# 字符串與正則表達式匹配 報錯
if ( "star" ~ "^star\.igrow\.cn$" ) {
break;
}
# 檢查文件類的 字符串與變量均可
if ( !-f "/data.log" ) {
break;
}
if ( !-f $filename ) {
break;
}
```
## return
### 語法
```
return code [text];
return code URL;
return URL;
return URI;
```
```
# return code [text]; 返回 ok 給客戶端
location = /ok {
return 200 "ok";
}
# return code URL; 臨時重定向到 百度
location = /redirect {
return 302 http://www.baidu.com;
}
# return URL; 和上面一樣 默認也是臨時重定向
location = /redirect {
return http://www.baidu.com;
}
```
## rewrite
使用正則表達式regex來匹配uri,匹配成功使用replacement替代uri
### 語法
```
rewrite regex replacement [flag]
```
### 代碼實例

### flag
* last:停止處理當前的`ngx_http_rewrite_module`的指令集,繼續搜索更改該location之外的匹配,相當于新來了一個請求。
* break:停止處理當前的`ngx_http_rewrite_module`的指令集,不挑出當前location中繼續處理
* redirect:返回客戶端302臨時重定向
* perment:返回301永久重定向
### 代碼實例
~~~
location / {
rewrite ^/test1 /test2;
rewrite ^/test2 /test3 last; # 此處發起新一輪location匹配 uri為/test3
rewrite ^/test3 /test4;
proxy_pass http://www.baidu.com;
}
location = /test2 {
return 200 "/test2";
}
location = /test3 {
return 200 "/test3";
}
location = /test4 {
return 200 "/test4";
}
# 發送如下請求
# curl 127.0.0.1:8080/test1
# /test3
當如果將上面的 location / 改成如下代碼
location / {
rewrite ^/test1 /test2;
# 此處 不會 發起新一輪location匹配;當是會終止執行后續rewrite模塊指令 重寫后的uri為 /more/index.html
rewrite ^/test2 /more/index.html break;
rewrite /more/index\.html /test4; # 這條指令會被忽略
# 因為 proxy_pass 不是rewrite模塊的指令 所以它不會被 break終止
proxy_pass https://www.baidu.com;
}
# 發送如下請求
# 瀏覽器輸入 127.0.0.1:8080/test1
# 代理到 百度產品大全頁面 https://www.baidu.com/more/index.html;
~~~
rewrite后面沒有flag時
1. location中會順序執行
2. location外也會被依次執行