Nginx与真实IP
Nginx与真实IP
FansUnion 发表于2年前
Nginx与真实IP
  • 发表于 2年前
  • 阅读 4
  • 收藏 0
  • 点赞 0
  • 评论 0

腾讯云 学生专属云服务套餐 10元起购>>>   

配置了Nginx,Tomcat中的Web程序,获得的ip一直是“127.0.0.1”,比较纳闷。
获得远程ip,已经判断了很多情况,为什么会这样呢?


 正解
 proxy_set_header        Host    $host;
 proxy_set_header        X-Real-IP       $remote_addr;
 proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
 
 Java代码直接取:request.getRemoteAddr();

 再有Nginx等情况下,获得的地址不对,比如“127.0.0.1”。


/**
 * 
 * @author fansunion@qq.com 2014年12月7日
 */
public class IpUtil {
public static String getRemoteIp(HttpServletRequest request) {
String remoteIp = request.getHeader("x-forwarded-for");
if (remoteIp == null || remoteIp.isEmpty()
|| "unknown".equalsIgnoreCase(remoteIp)) {
remoteIp = request.getHeader("X-Real-IP");
}
if (remoteIp == null || remoteIp.isEmpty()
|| "unknown".equalsIgnoreCase(remoteIp)) {
remoteIp = request.getHeader("Proxy-Client-IP");
}
if (remoteIp == null || remoteIp.isEmpty()
|| "unknown".equalsIgnoreCase(remoteIp)) {
remoteIp = request.getHeader("WL-Proxy-Client-IP");
}
if (remoteIp == null || remoteIp.isEmpty()
|| "unknown".equalsIgnoreCase(remoteIp)) {
remoteIp = request.getHeader("HTTP_CLIENT_IP");
}
if (remoteIp == null || remoteIp.isEmpty()
|| "unknown".equalsIgnoreCase(remoteIp)) {
remoteIp = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (remoteIp == null || remoteIp.isEmpty()
|| "unknown".equalsIgnoreCase(remoteIp)) {
remoteIp = request.getRemoteAddr();
}
if (remoteIp == null || remoteIp.isEmpty()
|| "unknown".equalsIgnoreCase(remoteIp)) {
remoteIp = request.getRemoteHost();
}
if (remoteIp != null && remoteIp.indexOf(",") != -1) {
remoteIp = remoteIp.substring(remoteIp.lastIndexOf(",") + 1,
remoteIp.length()).trim();
}
return remoteIp;
}
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

共有 人打赏支持
粉丝 52
博文 857
码字总数 825464
×
FansUnion
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: