详解nginx配置url重定向-反向代理

2019-10-17 19:08:58丽君

if ($args ^~ post=100){
 rewrite ^ http://example.com/new-address.html? permanent;
}

注意$args变量不会被编译,与location过程中的URI不同(参考http核心模块中的location)

示例:当访问www.lansgg.com的时候跳转到www.Aries.com;

 server {
  listen 80 default_server;
  server_name  www.lansgg.com lansgg.com;
  access_log  logs/lansgg.access.log main;
  error_log  logs/lansgg.error.log;
  root   /opt/nginx/nginx/html/lansgg;
  index index.html;
  rewrite ^/ http://www.Aries.com/;
  }

break 指令 可使用server, location, if 区域; 中止Rewirte,不在继续匹配

last 指令 可server, location, if  区域;

last与break的区别在于,last并不会停止对下面location的匹配。

测验一下break与last的区别

 server {
 listen 80 default_server;
 server_name www.lansgg.com lansgg.com;
 access_log logs/lansgg.access.log main;
 error_log logs/lansgg.error.log;
 root  /opt/nginx/nginx/html/lansgg;
 index index.html;
 location /c1.html {
 rewrite /c1.html /c2.html break;
 }
 location /c2.html {
 return 508;
 }
 }
[root@master sbin]# echo "c1" > /opt/nginx/nginx/html/lansgg/c1.html
[root@master sbin]# echo "c2" > /opt/nginx/nginx/html/lansgg/c2.html

使用break会停止匹配下面的location,直接发起请求www.lansgg.com/c1.html,他会显示c2的内容;


wKiom1ReJwmg3h4tAABlg5WLTFc650.jpg  

使用last的话,会继续搜索下面是否有符合条件(符合重写后的/c2.html请求)的location。此时,/c2.html刚好与面location的条件对应上了,进入花括号{}里面的代码执行,这里会返回508。

 server {
 listen 80 default_server;
 server_name www.lansgg.com lansgg.com;
 access_log logs/lansgg.access.log main;
 error_log logs/lansgg.error.log;
 root  /opt/nginx/nginx/html/lansgg;
 index index.html;
 location /c1.html {
 rewrite /c1.html /c2.html last;
 }
 location /c2.html {
 return 508;
 }
 }

使用firebug 可以看到;

wKiom1ReJ_bR_WwhAACvgot1dVM022.jpg

if 指令 可使用server, location 区域;

示例:当访问http://www.lansgg.com网址的时候跳转到www.Aries.com;

 server {
  listen 80 default_server;
  server_name  www.lansgg.com lansgg.com;
  access_log  logs/lansgg.access.log main;
  error_log  logs/lansgg.error.log;
  root   /opt/nginx/nginx/html/lansgg;
  index index.html;
  if ($http_host = www.lansgg.com){
  rewrite (.*) http://www.Aries.com;
  }
  }

wKioL1ReMavwbbrPAAEAO-or-Mg289.jpg

return 指令 可使用server, location, if  区域