6

java获取nginx反向代理后浏览器的真实ip

 2 years ago
source link: https://www.huhexian.com/21228.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

java获取nginx反向代理后浏览器的真实ip

2022-01-0414:34:41评论646字

若用nginx做反向代理后,直接用String ip = request.getRemoteAddr();

获取的将是nginx服务器所在ip地址,不能获取浏览器真实ip地址!

第一步:在nginx中添加如下配置:

  1. proxy_set_header Host $host;
  2. proxy_set_header X-Real-IP $remote_addr;
  3. proxy_set_header REMOTE-HOST $remote_addr;
  4. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

如下图所示:

java获取nginx反向代理后浏览器的真实ip

第二步:获取真实ip地址

  1. String ip = request.getHeader("x-forwarded-for");
  2. if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  3. ip = request.getHeader("Proxy-Client-IP");
  4. if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  5. ip = request.getHeader("WL-Proxy-Client-IP");
  6. if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  7. ip = request.getRemoteAddr();

这样,获取到的就是用户所在公网的ip地址了。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK