# nginx的rewrite語法詳解
[TOC]
## rewrite 使用環境
`Server` `location` `if`
## 重寫過程中可能用到的指令
~~~
if (條件) { // 設定條件在進行重寫
}
set # 設置變量
return # 返回狀態碼
break # 跳出rewrite
rewrite # 重寫
~~~
## rewrite模塊指令
| 指令 | 語法 | 默認值 |使用環境 |
|-|-|-|-|
| break | break | none | server, location, if |
| if (盡量考慮使用 trp_files 代替) | if (condition) { … } | none | server, location |
| return | return code | none | server, location, if |
| rewrite | rewrite regex replacement flag | none | server, location, if |
| rewrite_log | rewrite_log on/off | off | server, location, if |
|set | set variable value | none | server, location, if |
## `if` 語法
語法格式如下:
~~~
if + 空格 (條件) {
重寫模式
}
~~~
括號中的條件有如下幾種寫法:
* = 用來判斷相等,用于字符串的比較
* ~ 用正則來匹配(區分大小寫)
* ~* 用正則來匹配(不區分大小寫)
* `-f` `-d` `-e` 判斷是否為文件、是否為目錄和是否存在
## ecshop實戰重寫url
~~~
#add by luo for ecshop grobal rewrite
location /ecshop {
# 商品詳情頁 http://192.168.0.200/ecshop/goods.php?id=9 -> http://192.168.0.200/ecshop/goods-9.html
rewrite goods-(\d+)-.*\.html /ecshop/goods.php?id=$1;
# 文章詳情頁 http://192.168.0.200/ecshop/article.php?id=12 -> http://192.168.0.200/ecshop/article-12.html
rewrite article-(\d+)-.*\.html /ecshop/article.php?id=$1;
# 復雜欄目檢索頁 http://192.168.0.200/ecshop/category.php?category=3&display=list&brand=0&price_min=0&price_max=0&filter_attr=0&page=1&sort=goods_id&order=ASC#goods_list -> http://192.168.0.200/ecshop/category-3-b0-min0-max0-attr0-1-goods_id-ASC.html
rewrite category-(\d+)-b(\d+)-min(\d+)-max(\d+)-attr([\d\.]+)-(\d+)-(\w+)-(\w+)\.html /ecshop/category.php?id=$1&brand=$2&price_min=$3&price_max=$4&filter_attr=$5&page=$6&sort=$7&order=$8#goods_list;
# 欄目檢索頁 http://192.168.0.200/ecshop/category-3-b1-min200-max1700-attr167.229.202.199.html -> http://192.168.0.200/ecshop/category.php?id=3&brand=1&price_min=200&price_max=1700&filter_attr=167.229.202.199
rewrite category-(\d+)-b(\d+)-min(\d+)-max(\d+)-attr([\d\.]+).*\.html /ecshop/category.php?id=$1&brand=$2&price_min=$3&price_max=$4&filter_attr=$5;
# 欄目頁面 http://192.168.0.200/ecshop/category-2-b0.html -> http://192.168.0.200/ecshop/category.php?id=3&brand=1
rewrite category-(\d+)-b(\d+)-.*\.html /ecshop/category.php?id=$1&brand=$2;
}
~~~