# 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; } ~~~