09 nginx Rewrite(重写)详细解析

一:Rewrite(重写)详细解析

rewrite 重写html

 

重写中用到的指令apache

if  (条件) {}  设定条件,再进行重写服务器

set #设置变量日志

return #返回状态码code

break #跳出rewritehtm

rewrite #重写blog

 

 

If  语法格式ip

If 空格 (条件) {rem

    重写模式字符串

}

 

条件又怎么写?

答:3种写法

1: “=”来判断相等, 用于字符串比较

2: “~” 用正则来匹配(此处的正则区分大小写)

   ~* 不区分大小写的正则

3: -f -d -e来判断是否为文件,为目录,是否存在.

 

例子:

 

 if  ($remote_addr = 192.168.1.100) {

       return 403;

}

 

 

 if ($http_user_agent ~ MSIE) {

      rewrite ^.*$ /ie.htm;

       break; #(不break会循环重定向)

 }

 

 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) {

    set $isie 1;

 }

 

 if ($fastcgi_script_name = ie.html) {

    set $isie 0;

 }

 

if ($isie 1) {

     rewrite ^.*$ ie.html;

}

相关文章
相关标签/搜索