Nginx+Tomcat出現session丟失問題

Nginx做爲一個強大的Web服務器,有很強的功能。在Nginx+Tomcat是Java Web動靜分離的很好模型。可是,今天在配置過程當中,遇到了一個問題,就是沒法登陸。因爲以前在配置Apache的過程當中,遇到過相似的問題,因此我很快肯定了是因爲sessionId在cookies中引發。 web

那麼,咱們如何在Nginx中配置,以免這樣的事情呢?我是經過以下代碼來解決的。 shell

場景描述一下: 服務器

我有一個二級域名mvn.domain.com,以及一個web程序,部署到個人服務器中,訪問地址爲:http://localhost:8081/nexus,經過個人域名,我但願反向代理到個人本地地址中。因爲,我在部署本地應用的時候,不是連接到根目錄(即root),致使個人應用程序的sessionId存儲在/nexus的path下。而當我成功後,mvn.domain.com中,找不到對應的sessionId信息,致使會話失效。 cookie

解決方法一: session

域名使用mvn.domain.com/nexus,反向代理到http://localhost:8081/nexus,能夠解決如上問題。配置以下: dom

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設置到根路徑下。
spa

相關文章
相關標籤/搜索