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代码及配置。

原文地址:https://www.cnblogs.com/xiewenming/p/7380165.html