Nginx REWRITE阶段

 

 

 

   rewrite_log on ;#每次rewrite都会记录一条记录在errorlog里
error_log logs/xxx.log notice;
  location /first { rewrite /first(.*) /second$1 last; #表示重新开始匹配location rewrite 第一个参数 /first(.*)表示被替换的值 /second$1 表示要替换成的值 last(flag前面有解释) return 200 'first! '; } location /second { rewrite /second(.*) /third$1 break; #直接停止 #rewrite /second(.*) /third$1; return 200 'second! '; } location /third { return 200 'third! '; }
    

    location /redirect1 {
      rewrite /redirect1(.*) $1 permanent; #permanent表示直接返回301重定向
    }


    location /redirect2 {
      rewrite /redirect2(.*) $1 redirect; #redirect表示302重定向
    }


    location /redirect3 {
      rewrite /redirect3 http://www.baidu.com; #如过重定向里带有http或https则默认302重定向
    }


    location /redirect4 {
      rewrite /redirect4(.*) http://rewrite.taohui.tech$1 permanent; #虽然有http或https则应为flag是permanent 所以重定向是301
    }

 
[root@3 conf]# curl http://shop**.com.cn:8080/redirect3 -I #通过代码可以看到以下头部结果
HTTP/1.1 302 Moved Temporarily
Server: openresty/1.13.6.2
Date: Sun, 14 Apr 2019 08:44:19 GMT
Content-Type: text/html
Content-Length: 167
Connection: keep-alive
Location: http://www.baidu.com

这里要注意 假设设置了return 指令 又同时设置累error_page 指令 那么 return 将优先被执行 因为 处于SERVER_REWRITE阶段 执行在POSTREAD阶段后 所以先执行 error_page将不起作用

error_page 指令

error_page 404 /404.html

  error_page 404 500 502 /500.html;

  error_page 404=200 /xxx.png (当发生404时候 返回一张图片 返回码是200)

  location / {

    error_page 404 =@fallback;

  }

  location @fallback{

    proxy_pass http://backend;

  }

 

 

 if 指令

syntax: if(condition){....}

default: --

context:server、location

nginx.conf 演示

isten 8090;#监听端口
root html/;
location /first {
rewrite /first(.*) /second$1 last;#用replacement进行新的url地址匹配
return 200 'first!
';
}
location /second {
rewrite /second(.*) /third$1 break;
return 200 'second!
';
}
location /third {
return 200 'third!
';
}

 L 51-53

原文地址:https://www.cnblogs.com/jackey2015/p/10366121.html