java后端集群化专题

nginx配置https,反向代理给tomcat

2018-04-22  本文已影响39人  江江的大猪

nginx配置https反向代理给tomcat(tomcat无需配https)

最终结果:一台机器中的nginx将所有https请求全部代理给tomcat,将80端口的http请求永久重定向到https路径,实现全站的https。防火墙Firewall开放https和http服务,这样用户只能通过nginx访问网站,无法直接访问到tomcat,避免了用户直接用http访问tomcat。

openssl req -x509 -nodes -days 36500 -newkey rsa:2048 -keyout /etc/nginx/ssl/nginx.key -out /etc/nginx/ssl/nginx.crt

req是openssl证书请求的子命令
-newkey rsa:2048 -keyout private_key.pem 表示生成私钥(PKCS8格式)
-nodes 表示私钥不加密,若不带参数将提示输入密码
-x509表示输出证书
-days36500 为100年有效期,此后根据提示输入证书拥有者信息
-keyout 代表私钥全路径
-out 代表证书全路径
server {
    listen              443 ssl;
    server_name         localhost;
    ssl_certificate     /usr/local/nginx-1.12.2/nginx1/ssl/nginx.crt;
    ssl_certificate_key /usr/local/nginx-1.12.2/nginx1/ssl/nginx.key;
    location / {
        proxy_pass   http://localhost:8080;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-Forwarded-Proto https;
        proxy_set_header X-Real-IP $remote_addr;
    }
}
server {
    listen       80;
    server_name  localhost;
    # 返回301状态码,永久重定向
    rewrite ^(.*)$  https://$host$1 permanent;
}
<Valve className="org.apache.catalina.valves.RemoteIpValve"
       remoteIpHeader="x-forwarded-for"
       protocolHeaderHttpsValue="https"
       protocolHeader="x-forwarded-proto" />
//源码如下:  
if (protocolHeader != null) {  
    String protocolHeaderValue = request.getHeader(protocolHeader);  
    if (protocolHeaderValue == null) {  
        // don't modify the secure,scheme and serverPort attributes  
        // of the request  
    } else if (protocolHeaderHttpsValue.equalsIgnoreCase(protocolHeaderValue)) {  
        request.setSecure(true);  
        // use request.coyoteRequest.scheme instead of request.setScheme() because request.setScheme() is no-op in Tomcat 6.0  
        request.getCoyoteRequest().scheme().setString("https");  
          
        request.setServerPort(httpsServerPort);  
    } else {  
        request.setSecure(false);  
        // use request.coyoteRequest.scheme instead of request.setScheme() because request.setScheme() is no-op in Tomcat 6.0  
        request.getCoyoteRequest().scheme().setString("http");  
          
        request.setServerPort(httpServerPort);  
    }  
}  
<!--
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
       prefix="localhost_access_log" suffix=".txt"
       pattern="%h %l %u %t &quot;%r&quot; %s %b" />
-->
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
       prefix="localhost_access_log" suffix=".txt"
       pattern="%{X-Real-IP}i %l %u %t &quot;%r&quot; %s %b" />
上一篇 下一篇

猜你喜欢

热点阅读