設定 Nginx 和 Tomcat 存取 HTTPS 內容

設定 Nginx 和 Tomcat 存取 HTTPS 內容

我使用 nginx 作為 Tomcat 上 Java Spring Boot + Angular 應用程式的負載平衡器和反向代理。我總共有 3 台伺服器,其中 1 台有 nginx,另外兩台有託管應用程式。

我在 nginx 上設定了 HTTPS 和 SSL,以便使用者可以透過 HTTPS 進行通訊。透過以下配置,我可以透過 https 存取應用程式的登入頁面,但是當我單擊登入按鈕時,我在控制台中收到錯誤

混合內容:「https://example/app/login」處的頁面是透過 HTTPS 載入的,但請求了不安全的 XMLHttpRequest 端點「http://172.16.1.70:8081/app/api/login」。該請求已被阻止;內容必須透過 HTTPS 提供。

這是我的 Nginx 配置

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    access_log  logs/access.log;
    
    # Load Balancer Setup
    upstream tomcat {
        server 172.168.1.10:8443;
        server 172.168.1.15:8443;
        ip_hash;
    }
    server {
        listen 80 ;
        listen  443 ssl http2;
        
        server_name  localhost;
        ssl_certificate      C:/ssl/sslcert.pem;
        ssl_certificate_key  C:/ssl/sslcert-key.pem;
        ssl_ciphers  HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers  on;
        ssl_session_cache    shared:SSL:1m;
        ssl_session_timeout  5m;
                
    location /app {
        proxy_read_timeout 120;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_cookie_path ~*^/.* /;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass http://tomcat;
        }
    
    # Auto redirect to https
    if ($scheme != "https") {
        return 301 https://$host$request_uri;
        }
    
    # Auto redirect to localhost/app
    location / {
        return 307 /app;
        }
    }
}

這是我的 tomcat server.xml 配置

<Connector port="8081" protocol="HTTP/1.1"
               connectionTimeout="20000"              
               redirectPort="8443"/>
               
    <Connector port="8443" protocol="HTTP/1.1"
           connectionTimeout="20000"
           proxyPort="443"
           scheme="https" secure="true"
            />

我嘗試透過檢查網路標籤進行偵錯,它以某種方式將登入頁面重定向到http://172.168.1.10:8081/app/api/login代替http://172.168.1.10:8443/app/api/login

我該如何解決這個問題,任何幫助將不勝感激。

答案1

配置後端伺服器以提供指向反向代理的 URL。對於 Tomcat,這通常是透過連接器上的proxyName和屬性來完成的。proxyPort你錯過了前者。

根據 Tomcat 上運行的應用程式的建置方式,可能還需要在某些應用程式特定的配置中對其進行配置。

相關內容