04_nginx之rewrite

2017-10-19  本文已影响0人  对方不想理你并向你抛出一个异常

rewrite 重写

重写中用到的指令

if  (条件) {}  设定条件,再进行重写 
set #设置变量
return #返回状态码 
break #跳出rewrite
rewrite #重写

If  语法格式
If 空格 (条件) {
    重写模式
}

条件又怎么写?

        location / {
            if ($remote_addr = 192.168.175.1) {
                return 403;
            }
            root   html;
            index  index.html index.htm;
        }
        location / {
            if ($http_user_agent ~ Chrome){
                rewrite ^.*$ /chrome.html;
                break;
            }
            root   html;
            index  index.html index.htm;
        }

注意:break是为了防止循环重定向

chrome浏览器访问
IE浏览器访问
location / {
            if (!-e $document_root$fastcgi_script_name){
                rewrite ^.*$ /404.html;
            }
            root   html;
            index  index.html index.htm;
        }
没有break,报错
location / {
            if (!-e $document_root$fastcgi_script_name){
                rewrite ^.*$ /404.html;
                break;
            }
            root   html;
            index  index.html index.htm;
        }
重定向到404

注意:此处还要加break,以 http://z.com/abc.html这个不存在页面为例,我们观察访问日志, 日志中显示的访问路径,依然是GET /abc.html HTTP/1.1
提示: 服务器内部的rewrite和302跳转不一样,跳转的话URL都变了,变成重新http请求404.html, 而内部rewrite, 上下文没变,就是说 fastcgi_script_name 仍然是 abc.html,因此 会循环重定向。

            if ($http_user_agent ~* msie) {
                set $isie 1;
            }

            if ($fastcgi_script_name = ie.html) {
                set $isie 0;
            }

            if ($isie 1) {
                rewrite ^.*$ ie.html;
            }

商城URL重写

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重写时, 正则里如果有”{}”,正则要用双引号包起来

上一篇 下一篇

猜你喜欢

热点阅读