基于java配置nginx获取真实IP代码实例

2025-05-29 0 66

1、java代码

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30
/** 获取客户端IP */

public static final String getClientIp(HttpServletRequest request) {

String ip = request.getHeader("X-Forwarded-For");

if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)|| "127.0.0.1".equalsIgnoreCase(ip)) {

ip = request.getHeader("Proxy-Client-IP");

}

if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)|| "127.0.0.1".equalsIgnoreCase(ip)) {

ip = request.getHeader("WL-Proxy-Client-IP");

}

if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)|| "127.0.0.1".equalsIgnoreCase(ip)) {

ip = request.getHeader("X-Real-IP");

}

if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)|| "127.0.0.1".equalsIgnoreCase(ip)) {

ip = request.getRemoteAddr();

}

if (StringUtils.isBlank(ip) ||"127.0.0.1".equals(ip)|| ip.indexOf(":") > -1) {

try {

ip = InetAddress.getLocalHost().getHostAddress();

} catch (UnknownHostException e) {

ip = null;

}

}

// 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割

if (ip != null && ip.length() > 15) {

if (ip.indexOf(",") > 0) {

ip = ip.substring(0, ip.indexOf(","));

}

}

return ip;

}

2、nginx需要进行相应修改,重点 proxy_set_header

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32
server {

listen xxxx;

server_name 127.0.0.1;

# 静态页面目录

root xxxxxxxxxx;

# 默认首页

index login.html;

proxy_set_header Host $http_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;

add_header Access-Control-Allow-Origin *;

add_header Access-Control-Allow-Methods 'GET,POST';

add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';

#proxy_cookie_path /* /*;

client_max_body_size 100m;

location / {

proxy_set_header Host $http_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;

proxy_set_header Upgrade $http_upgrade;

proxy_set_header Connection "upgrade";

add_header Access-Control-Allow-Origin *;

add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';

add_header Access-Control-Allow-Methods GET,POST,OPTIONS;

......

}

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持快网idc。

原文链接:https://www.cnblogs.com/xiufengd/p/13625361.html

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 基于java配置nginx获取真实IP代码实例 https://www.kuaiidc.com/117209.html

相关文章

发表评论
暂无评论