作者:fbysss
典型场景:
Tomcat的webapps目录中,有两个应用:app1、app2,如果没有nginx,我们的访问路径为:
http://www.domainname.com:8080/app1 http://www.domainname.com:8080/app2
端口号暴露给用户很不好看也不安全。修改Tomcat配置文件的做法,也可以,但感觉麻烦一些,在这里并不推荐。让用户感觉不到Tomcat的存在,并让Tomcat服务器安全的藏在Nginx后面,是我们的目的。

我们希望用户通过以下地址来访问:

http://app1.domainname.com

http://app2.domainname.com

比如我们在配置Maven私服Nexus的时候就如此,其默认的路径是http://localhost:8081/nexus,我们希望通过nexus.domainname.com来访问。


解决办法:

首先,域名解析,这一步不用在这里说了。如果只是内部实验,将app1.domainname.com、app2.domainname.com配置在客户端hosts文件中即可。


然后,开始修改nginx.conf


如果不考虑集群,使用proxy_pass 目的地址即可转发。


于是,我们自然想到,在server节点中应该有如下配置(下面就以nexus为例,如果是多个应用,配置多个server即可):


server {
        listen 80;
        server_name nexus.domainname.com;
        location /{
           index index.html index.htm index.jsp;
           proxy_pass http://xx.xx.xx.xx:8081/nexus;
        }
     }




问题1:浏览器(chrome)告诉我们,此网页包含重定向循环,此时地址栏显示的地址是http://nexus.domainname.com//通过查找相关资料,在路径proxy_pass这句话中,nexus后面加一个斜杠/,就可以正常转向了。

问题2:访问应用的时候,发现遇到用户认证的时候,自然返回到登录页了。这是啥子情况?此时,如果是一般的tomcat应用,地址栏上,后面会跟上,jsessionId=xxxxxx,而且每次访问都不同。

分析:我们可以猜想,session失效了。

解决:原来,这里存在一个cookie路径的配置问题。原理可参考文章:http://030710314.iteye.com/blog/2095819增加一行proxy_cookie_path /nexus /;即可。

server {
        listen 80;
        server_name nexus.domainname.com;
        location /{
           index index.html index.htm index.jsp;
           proxy_pass http://xx.xx.xx.xx:8081/nexus/;
           proxy_cookie_path /nexus /;
        }
    }




这种配法,地址栏中的地址,也很优雅。


顺便提及另外一种做法:


server {
        listen 80;
        server_name nexus.domainname.com;
        location /{
           index index.html index.htm index.jsp;
           proxy_pass http://xx.xx.xx.xx:8081;
           rewrite ^/$ /nexus last;
        }
    }



这种配法,原理很简单,就是仅仅帮你做了一步,访问站点时,自动转发路径到nexus,省得输入。其他该怎样怎样。所以也不用管cookie的事情。


不过缺点就是,地址栏上显示的地址不好看,还是带子目录的。


所以,对于第一种配法:


proxy_pass http://xx.xx.xx.xx:8081/nexus/;
           proxy_cookie_path /nexus /;



还有一种写法可以达到同样效果:


proxy_pass http://xx.xx.xx.xx:8081;
           rewrite /(.*)$    /nexus/$1 break;
           proxy_cookie_path /nexus /;


问题3:

解决了端口和子目录的问题之后,新的问题可能存在。

比如,有些地方,我们在Java代码里面将contextPath写死了。用于拼接url。String ctx = request.getContextPath();//这里取出来的肯定还是带子目录的。因为其由应用服务器决定,与nginx配置无关。

修改Java代码显然不是好的方法。

rewrite可以帮助我们解决问题。

增加一句: 

rewrite /nexus(.*)$ /$1 permanent;

即可——注意如果用last的话,地址栏不会更新。

当然。如果为了避免其他路径里面也有nexus,可以将其放在location ~/nexus里面。或者有更严格的正则表达式。




PS:

1.修改了配置文件,别忘了使用nginx -s reload重载配置文件。

2.这个例子使用nexus,只是简单示意,如果是在配置私服上有问题,可参考:

http://books.sonatype.com/nexus-book/reference/install-sect-proxy.html

要注意BASE_URL的配置,要配置为全路径,不带nexus,还要将Force Base URL打钩——nexus的静态资源的根路径应该会通过这个来读取。出现404无法加载某个资源的问题。

3.如果proxy_cookie_path /nexus / 出现问题,尝试proxy_cookie_path /nexus/ /

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: nginxTomcat