1. 程式人生 > 其它 >解決方案---使用域名訪問web服務導致後端session失效,而使用ip不會

解決方案---使用域名訪問web服務導致後端session失效,而使用ip不會

技術標籤:nginxjavaweb伺服器session

專案使用docker部署,在使用ip測試的時候沒有問題。當把域名繫結到ip後,通過域名訪問會出現後端session失效的問題。

  • 原nginx.conf如下:
#user  root;
worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    server {
        listen       80;
        server_name  localhost; 
        location / {
            root   /usr/share/nginx/html; # 對應nginx的放html地址
			try_files $uri $uri/ /index.html last; # 這裡也需要手寫進去
            index  index.html index.htm;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}
  • 解決方案
#user  root;
worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    server { #監聽前端
        listen       80;
        server_name  你的域名;

        location / {
            root   /usr/share/nginx/html; # 對應nginx的放html地址
            try_files $uri $uri/ /index.html last; # 這裡也需要手寫進去
            index  index.html index.htm;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
    server { #監聽後端請求
        listen 8081;
        server_name  你的域名; # 取決於前端請求後端的baseurl
        location / {
                proxy_pass http://127.0.0.1:8081/; # 我的後端專案埠號是8081
                proxy_cookie_path / /;
                proxy_set_header Cookie $http_cookie;
                proxy_set_header   Host             $host;
                proxy_set_header   X-Real-IP        $remote_addr;
                proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
        }
   }
}