Nginx配置X-Forwarded-Proto


需求

最近公司在做全站https,架構上面有Nginx+tomcat Nginx+php,且nginx配置了ssl,tomcat和php項目使用https協議

但是,發送的是https url請求,php和tomcat的log里面記錄的都是http的請求。

解決方法很簡單,只需要分別配置一下 Nginx 和 Tomcat 就好了,而不用改程序。

配置 Nginx 的轉發選項:
server {
    listen       443 ssl http2;
    server_name  new.m.abc.com m.abc.com;
    ssl on;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers 'AES128+EECDH:AES128+EDH:!aNULL';
    ssl_prefer_server_ciphers on;
    ssl_session_cache shared:SSL:10m;
    ssl_dhparam /etc/nginx/conf.d/ssl/dhparam.pem;
    ssl_certificate     /etc/nginx/conf.d/ssl/abc.com.crt;
    ssl_certificate_key /etc/nginx/conf.d/ssl/abc.com.key;
    add_header Strict-Transport-Security "max-age=63072000; includeSubdomains; preload";
    access_log  /var/log/nginx/new.m.abc.log main;
    set $web_url $host;
    if ($request_uri ~* /h5/index.html)
        {
           rewrite ^/(.*)$ http://m.abc.com permanent;
        }
    limit_req zone=anti_spider burst=1 nodelay;
     if ($http_user_agent ~* "qihoobot|Mediapartners-Google|Adsbot-Google|Feedfetcher-Google|Yahoo! Slurp|Yahoo! Slurp Ch
ina|YoudaoBot|Sosospider|Sogou spider|Sogou web spider|MSNBot|ia_archiver|Tomato Bot")
    {
    set $anti_spider $http_user_agent;
    }
    location / {
        proxy_pass         http://web.server;
        proxy_set_header   Host             $host;
        proxy_set_header   X-Real-IP        $remote_addr;
        proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        set $domain default;
        }
}

proxy_set_header X-Forwarded-Proto $scheme;

配置Tomcat server.xml 的 Engine 模塊下配置一個 Valve:
<Valve className="org.apache.catalina.valves.RemoteIpValve"  
remoteIpHeader="X-Forwarded-For"  
protocolHeader="X-Forwarded-Proto"  
protocolHeaderHttpsValue="https"/>  

配置雙方的 X-Forwarded-Proto 就是為了正確地識別實際用戶發出的協議是 http 還是 https。

測試就都變為正確的結果了,就像用戶在直接訪問 Tomcat 一樣。

如果是php提供服務,無需修改php代碼及配置。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM