apache反向代理tomcat時x-forwarded-for為null的問題
apache 在用ProxyPass時會自動在header中設定X-Forwarded-For X-Forwarded-Host和X-Forwarded-Server (http://httpd.apache.org/docs/2.2/mod/mod_proxy.html)
如果tomcat後端不做設定, 在jsp中用out.println("x-forwarded-for:" + request.getHeader("x-forwarded-for") + "<br>");能獲取到客戶ip,
由於在用nginx做前置代理時為了https也能訪問,要讓out.println("x-forwarded-proto:" + request.getHeader("x-forwarded-proto") + "<br>");能獲取到真實的值需要在tomcat的server.xml
中設定value:
<Valve
className="org.apache.catalina.valves.RemoteIpValve"
remoteIpHeader="x-forwarded-for"
protocolHeader="x-forwarded-proto"
/>
這樣設定後的tomcat,用於Apache做前置代理時request.getHeader("x-forwarded-for")獲取到null。在https://tomcat.apache.org/tomcat-7.0-doc/api/org/apache/catalina/valves/RemoteIpValve.html
中有:
所有在tomcat的server.xml中設定了上述引數後會造成request.getHeader("x-forwarded-for")獲取的值為null,但用request.getRemoteAddr()就能獲取真實客戶ip了。
另外要用request.getHeader("x-forwarded-proto")獲取值需要在apache設定中加入RequestHeader set X-Forwarded-Proto "https"(在https的設定中,在http設定中用http)