rewrite 重写php
重写中用到的指令html
if (条件) {} 设定条件,再进行重写 nginx
set #设置变量正则表达式
return #返回状态码 apache
break #跳出rewrite浏览器
rewrite #重写服务器
If 语法格式ide
If 空格 (条件) {url
重写模式spa
}
条件又怎么写?
答:3种写法
1: “=”来判断相等, 用于字符串比较
2: “~” 用正则来匹配(此处的正则区分大小写)
~* 不区分大小写的正则
3: -f -d -e来判断是否为文件,为目录,是否存在.
例子:
若是192.168.1.100访问,则返回状态403
if ($remote_addr = 192.168.1.100) {
return 403;
}
nginx自带404:
if ($http_user_agent ~ MSIE) {
rewrite ^.*$ /ie.htm;
break; #(不break会循环重定向)
}
若是是ie浏览器访问,则无论访问什么都访问ie.html文件:
(可是上面会形成n次重定向:ie访问一次就rewrite一次,而后又访问又rewrite...)
重写404:
if (!-e $document_root$fastcgi_script_name) {
rewrite ^.*$ /404.html break;
}
注, 此处还要加break,
以 xx.com/dsafsd.html这个不存在页面为例,
咱们观察访问日志, 日志中显示的访问路径,依然是GET /dsafsd.html HTTP/1.1
提示: 服务器内部的rewrite和302跳转不同.
跳转的话URL都变了,变成从新http请求404.html, 而内部rewrite, 上下文没变,
就是说$fastcgi_script_name仍然是 dsafsd.html,所以 会循环重定向.
set 是设置变量用的, 能够用来达到多条件判断时做标志用.
达到apache下的 rewrite_condition的效果
以下: 判断IE并重写,且不用break; 咱们用set变量来达到目的(这样作意义不大)
if ($http_user_agent ~* msie) { #(~* msie:不区分大小写匹配msie)
set $isie 1;
}
if ($fastcgi_script_name = ie.html) {
set $isie 0;
}
if ($isie 1) {
rewrite ^.*$ ie.html;
}
(若是访问者是ie,且访问的不是ie.html,则重写)
Rewrite语法
Rewrite 正则表达式 定向后的位置 模式
Goods-3.html ---->Goods.php?goods_id=3
goods-([\d]+)\.html ---> goods.php?goods_id =$1
location /ecshop {
index index.php;
rewrite goods-([\d]+)\.html$ /ecshop/goods.php?id=$1;
rewrite article-([\d]+)\.html$ /ecshop/article.php?id=$1;
rewrite category-(\d+)-b(\d+)\.html /ecshop/category.php?id=$1&brand=$2;
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;
rewrite category-(\d+)-b(\d+)-min(\d+)-max(\d+)-attr([\d+\.])-(\d+)-([^-]+)-([^-]+)\.html /ecshop/category.php?id=$1&brand=$2&price_min=$3&price_max=$4&filter_attr=$5&page=$6&sort=$7&order=$8;
}
注意:用url重写时, 正则里若是有”{}”,正则要用双引号包起来