問題
項目訪問使用nginx做反向代理,打印日誌時所有的請求ip都變成了127.0.0.1
解決辦法
##1.nginx.conf 配置文件修改
location / {
proxy_pass http://127.0.0.1:10678;
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;
}
代碼中獲取ip方式變更
/**
* 獲取 IP地址
* 使用 Nginx等反向代理軟件, 則不能通過 request.getRemoteAddr()獲取 IP地址
* 如果使用了多級反向代理的話,X-Forwarded-For的值並不止一個,而是一串IP地址,
* X-Forwarded-For中第一個非 unknown的有效IP字符串,則爲真實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 "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
}