Nginx作爲一個強大的Web服務器,有很強的功能。在Nginx+Tomcat是Java Web動靜分離的很好模型。但是,今天在配置過程中,遇到了一個問題,就是無法登錄。由於之前在配置Apache的過程中,遇到過類似的問題,所以我很快確定了是由於sessionId在cookies中引起。
那麼,我們如何在Nginx中配置,以避免這樣的事情呢?我是通過如下代碼來解決的。
場景描述一下:
我有一個二級域名mvn.domain.com,以及一個web程序,部署到我的服務器中,訪問地址爲:http://localhost:8081/nexus,通過我的域名,我希望反向代理到我的本地地址中。由於,我在部署本地應用的時候,不是鏈接到根目錄(即root),導致我的應用程序的sessionId存儲在/nexus的path下。而當我成功後,mvn.domain.com中,找不到對應的sessionId信息,導致會話失效。
解決方法一:
域名使用mvn.domain.com/nexus,反向代理到http://localhost:8081/nexus,可以解決如上問題。配置如下:
location /nexus/ {
proxy_pass http://localhost:8081/nexus/;
proxy_redirect off;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Cookie $http_cookie;
chunked_transfer_encoding off;
}
location / {
proxy_pass http://localhost:8081/nexus/;
proxy_redirect http://localhost:8081/ http://mvn.domain.com/;
}
location / {
proxy_pass http://localhost:8081/nexus/;
proxy_redirect off;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Cookie $http_cookie;
rewrite ^/nexus/(.*)$ /$1 last;
proxy_cookie_path /nexus /;
chunked_transfer_encoding off;
}
說明:
1. 通過proxy_pass 來確定對應目錄的跳轉
2. 在多層代理中,填充Header請求頭(proxy_set_header)
3. 將應用中訪問的nexus路徑rewrite到根路徑下。
4. 將cookie_path爲/nexus設置到根路徑下。