700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > Nginx+Tomcat+SSL 识别 https还是http

Nginx+Tomcat+SSL 识别 https还是http

时间:2024-04-25 11:58:44

相关推荐

Nginx+Tomcat+SSL 识别 https还是http

实际上, 大规模的网站都有很多台Web服务器和应用服务器组成,用户的请求可能是经由 Varnish、HAProxy、Nginx之后才到应用服务器,中间有好几层。而中小规模的典型部署常见的是 Nginx+Tomcat 这种两层配置,而Tomcat 会多于一台,Nginx 作为静态文件处理和负载均衡。

如果Nginx作为前端代理的话,则Tomcat根本不需要自己处理 https,全是Nginx处理的。用户首先和Nginx建立连接,完成SSL握手,而后Nginx 作为代理以 http 协议将请求转给 tomcat 处理,Nginx再把 tomcat 的输出通过SSL 加密发回给用户,这中间是透明的,Tomcat只是在处理 http 请求而已。因此,这种情况下不需要配置 Tomcat 的SSL,只需要配置 Nginx 的SSL 和 Proxy。

在代理模式下,Tomcat 如何识别用户的直接请求(URL、IP、https还是http )?

在透明代理下,如果不做任何配置Tomcat 认为所有的请求都是 Nginx 发出来的,这样会导致如下的错误结果:

request.getScheme() //总是 http,而不是实际的http或httpsrequest.isSecure() //总是false(因为总是http)request.getRemoteAddr() //总是 nginx 请求的 IP,而不是用户的IPrequest.getRequestURL() //总是 nginx 请求的URL 而不是用户实际请求的 URLresponse.sendRedirect( 相对url ) //总是重定向到 http 上 (因为认为当前是 http 请求)

如果程序中把这些当实际用户请求做处理就有问题了。解决方法很简单,只需要分别配置一下 Nginx 和 Tomcat 就好了,而不用改程序。

配置 Nginx 的转发选项:

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;

配置Tomcat server.xml 的 Engine 模块下配置一个 Value:

<Valve className="org.apache.catalina.valves.RemoteIpValve" remoteIpHeader="X-Forwarded-For"protocolHeader="X-Forwarded-Proto" protocolHeaderHttpsValue="https"/>

配置双方的 X-Forwarded-Proto 就是为了正确地识别实际用户发出的协议是 http 还是 https。X-Forwarded-For 是为了获得实际用户的 IP。

这样以上5项测试就都变为正确的结果了,就像用户在直接访问 Tomcat 一样。

文章参考:负载均衡配置

# nginx 部分配置参考server {server_name ;listen 443;index index.jsp;ssl on;ssl_certificate /mnt/releaseCert/serverbundle.crt;ssl_certificate_key /mnt/releaseCert/serverbundle.key;if ($request_uri ~* "\.html$"){rewrite ^/(.*)$ http://$host/$1 redirect;}location / {proxy_pass http://10.171.27.25:9002; # 内网IPproxy_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;}}server{server_name ;listen 80;index index.jsp;if ($request_uri ~* "/pmcs/$"){rewrite ^/(.*)$ https://$host/$1 redirect;}if ($request_uri ~* "/pmcs/login.jsp$"){rewrite ^/(.*)$ https://$host/$1 redirect;}location / {proxy_pass http://10.171.27.25:9002;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;}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。