出自:http://rguess.iteye.com/blog/2079618
nginx代理tomcat的時候,tomcat獲取的客戶端不是客戶端傳過來的ip,出現這種情況的原因很明顯,nginx作爲代理服務器先攔截客戶端發來的請求,它再以localhost的身份轉發給tomcat去處理。解決辦法在nginx配置中的location節點中加入以下:
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header REMOTE-HOST $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
java可以這樣獲取遠程ip
- public static String getIpAddr(HttpServletRequest request) {
- String ip = request.getHeader("x-forwarded-for");
- if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
- ip = request.getHeader("Proxy-Client-IP");
- }
- if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
- ip = request.getHeader("WL-Proxy-Client-IP");
- }
- if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
- ip = request.getRemoteAddr();
- }
- return ip;
- }