nginx的prox_pass与rewrite

nginx的rewrite地址重写与proxy_pass模块

参考链接:http://www.jb51.net/article/78746.htm

在配置nginx的二级目录以及rewrite时,可以结合日志信息进行调试。

1. 在nginx里面,可以对后端的tomcat,php服务进行做反向代理,即会用到 proxy_pass 模块,例如
 普通的反向代理:
----nginx
  location ~ /* {
    proxy_pass http://127.0.0.1:8008;
   }
 或者可以
  location / {
    proxy_pass http://127.0.0.1:8008;
   }
----apache
  ProxyPass /ysz/ http://localhost:8080/   
   
2. 复杂点的反向代理:(匹配正则)
 比如将url中以 /jgg/ 开头的请求转发到后端的server上(后端server为127.0.00.1:9091),可以在nginx里面设置一个变量,来临时保存/jgg/后面的路径信息。
 location ^~ /jgg/ {
   if ($request_uri ~ /jgg/(\d+)/(.+)) {
      set $bucketid $1;
      set $params $2;
       }
    proxy_pass http://mx$bucketid.test.com:6601/$params;
    }
或者
   location ^~ /jgg/ {
            #  proxy_pass http://127.0.0.1:9091/jgg/awardSetup/init;  (这种转发是相当于写死的,只要匹配到jgg,全部转发到http://127.0.0.1:9091/jgg/awardSetup/init)


             if ( $request_uri ~ /jgg/(.*)) {     
            proxy_pass http://127.0.0.1:9091/jgg/$1;
            }
    }        

   这个上面是将匹配的jgg后面所有参数都转发到后端server。就像我们在访问一个网页的时候会出来一串参数字符(http://jgg.marketing.yunpaas.cn/jgg/activity/startDrawAward?id=1),然后把
访问http://center.marketing.yunpaas.cn/jgg/activity/startDrawAward?id=1 这个地址,他回去自动转到 127.0.0.1:9091下的jgg/activity/startDrawAward?id=1

----apache
  ProxyPassMatch ^/wap/(.*)$  http://192.168.132.147/$1
  
   if ($host ~* www.(.*)){
        set $host_without_www $1;
        rewrite (.*)$ http://$host_without_www/www$1;
    }

自己感觉,在proxy_pass里面所添加的$1这种变量都是针对正则部分进行选择的位置变量。 

3. url的/问题
在nginx中配置proxy_pass时,当在后面的url加上了/,相当于是绝对根路径,则nginx不会把location中匹配的路径部分代理走;如果没有/,则会把匹配的路径部分也给代理走。

下面四种情况分别用http://192.168.1.4/proxy/test.html 进行访问。

第一种:
location /proxy/ {
     proxy_pass http://127.0.0.1:81/;
}
会被代理到http://127.0.0.1:81/test.html 这个url
 
第二种 (相对于第一种,最后少一个 /)
location /proxy/ {
     proxy_pass http://127.0.0.1:81;
}
会被代理到http://127.0.0.1:81/proxy/test.html 这个url

4. ### 注释:两种情况不能使用代理转发
  1. 如果location段里面使用了正则,则不能进行使用proxy_pass。
  2. 执行代理动作的location段内使用了rewrite指令对location URI进行了修改,并且使用rewrite后的配置发出请求(break)。
  
  $request_uri 变量的使用,if、$request_uri、rewrite使用  (request_uri请求)
  
   #    if ( $request_uri ~ '.*\.(html|htm|gif|jpg|jpeg|bmp|png|ico|txt|js|css)$') {
       #         rewrite '.*\.(html|htm|gif|jpg|jpeg|bmp|png|ico|txt|js|css)$' http://zhifu.qc.cn:9999 redirect;
       #       }
  
  案列:一个二级目录的地址重写
   location ^~ /static/ {
                proxy_pass http://127.0.0.1:88/;
            rewrite ^/(http://soso.yun.cn/static/*)  http://127.0.0.1:88/$1 permanent;









  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值