编程小贴士

给你的编程提供小点子


在tomcat应用中获得原始IP

Apache/Nginx 通常被放在tomcat前作为http代理。

browser -> apache -> tomcat

但是缺点是丢失了很多原有的网络信息:ip、hostname、protocol(用的是http还是 https)

比如,当java程序想生成http重定向请求的时候会遇到麻烦。因为HTTP头部的Location字段的值必须是绝对URL。重定向的问题勉强可以 交给前面的proxy来解决(让apache重写header),但是藏在http body中的各种链接问题就棘手多了。比如当从一个html页面载入一个外部资源时,资源的链接到底是写http的还是https的呢?

通过修改apache和tomcat的配置,可以让这个问题得到较为完美的解决。
首先是要apache把这些丢失的信息通过http header发到后面去。
1. Host字段

HTTP头部的Host字段用来写网站的域名。如果服务器(此处指tomcat)需要支持virtual host,即同一个IP服务多个域名,那么这个字段很重要。

在配置mod_proxy时加上ProxyPreserveHost,就会让apache往后端转发的时候,Host字段依然填它从browser收到的那个域名。

2. Apache默认会发送的字段

默认情况下apache在做http逆向代理时会给后端发送以下字段

X-Forwarded-For client的IP地址

X-Forwarded-Host client所请求的域名,即client发来的的http header中Host字段的值。

X-Forwarded-Server 这台代理服务器(apache)的域名。

3. 需要添加的

纵使有了以上信息,我们还是不知道client用的到底是http还是https访问的apache。所以要加下面这行:

RequestHeader set X-Forwarded-Proto “https” env=HTTPS

这行代码的意思是,如果当前含有“HTTPS”这个环境变量,那么往后端转发请求时,在头部加上X-Forwarded-Proto字段,值为”https”。

类似的还可添加其它信息。如HTTPS/SPDY的具体信息,假如前端用的是spdy,那么当前请求不仅具有HTTPS这个环境变量,还有一个名为SPDY_VERSION的环境变量,它的值就是spdy 的版本号。

RequestHeader set X-SPDY-VERSION “%{SPDY_VERSION}e” env=SPDY_VERSION

等等。其它需要什么添加什么。如果想知道apache有哪些环境变量,把以下三行保存为php文件放到apache上,然后用浏览器访问一下就知道了。

<?php

phpinfo();

?>
其次,是让tomcat理解这些额外的header。
tomcat的Valves,能在收到请求时拦截并修改相应的值。https://tomcat.apache.org/tomcat-7.0-doc/config/valve.html

其中与我在此讨论的问题相关的是org.apache.catalina.valves.RemoteIpValve。它的主要功能是:

1. replaces the apparent client remote IP address and hostname for the request with the IP address list presented by a proxy or a load balancer via a request headers (e.g. “X-Forwarded-For”).

2. replaces the apparent scheme (http/https) and server port with the scheme presented by a proxy or a load balancer via a request header (e.g. “X-Forwarded-Proto”).

简单点说,就是把下面这行代码添加到tomcat的server.xml中的Engine或Host element下。

<Valve  className=”org.apache.catalina.valves.RemoteIpValve”    remoteIpHeader=”x-forwarded-for”    proxiesHeader=”x-forwarded-by”    protocolHeader=”x-forwarded-proto”    />

然后写个servlet测试下,看看对不对:

public class DumpHeaders extends HttpServlet {
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
    response.setContentType("text/plain");
    response.setCharacterEncoding("UTF-8");
    try(java.io.PrintWriter writer=response.getWriter()){
      writer.println("isSecure:"+request.isSecure());
      writer.println("server name:"+request.getServerName());
      writer.println("remote addr:"+request.getRemoteAddr());
      writer.println("headers:");
      java.util.Enumeration<String> names=request.getHeaderNames();
      while(names.hasMoreElements()){
        String headerName=names.nextElement();
        java.util.Enumeration<String> values=request.getHeaders(headerName);
        while(values.hasMoreElements()){
          String headerValue=values.nextElement();
          writer.println(headerName+"\t"+headerValue);
        }
      }
    }
  }
}

HTTP下:
isSecure:false
server name:www.sunchangming.com
remote addr:60.10.169.130
headers:
host  www.sunchangming.com
accept  text/html, application/xhtml+xml, */*
accept-language  zh-CN
user-agent  Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko
accept-encoding  gzip, deflate
cache-control  no-cache
connection  Keep-Alive
x-forwarded-host  www.sunchangming.com
x-forwarded-server  www.sunchangming.com

HTTPS下:
isSecure:true
server name:www.sunchangming.com
remote addr:60.10.169.130
headers:
host  www.sunchangming.com
accept  text/html, application/xhtml+xml, */*
accept-language  zh-CN
user-agent  Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko
accept-encoding  gzip, deflate
cache-control  no-cache
x-forwarded-proto  https
connection  Keep-Alive
x-forwarded-host  www.sunchangming.com
x-forwarded-server  www.sunchangming.com

本文转自:IT技术博客大学习

67 Responses to “ 在tomcat应用中获得原始IP ”

  1. suba suba说道:

    3FtbFo Well I definitely enjoyed reading it. This subject provided by you is very useful for accurate planning.

  2. chocopie说道:

    3l2mk7 I really liked your article.Really thank you! Will read on

  3. This is one awesome blog article.Really looking forward to read more. Much obliged.

  4. casino gambling说道:

    recognize his kindness are cost-free to leave donations

  5. w88world说道:

    Im grateful for the article.Much thanks again. Keep writing.

  6. Thank you for sharing this good piece. Very inspiring! (as always, btw)

  7. Some really select content on this internet site , saved to bookmarks.

  8. woking cab说道:

    There is definately a lot to know about this topic. I like all of the points you made.

  9. gia sat thep说道:

    Way cool! Some very valid points! I appreciate you writing this article plus the rest of the website is also very good.

  10. Way cool! Some extremely valid points! I appreciate you writing this post and also the rest of the site is really good.

  11. more details说道:

    Whispering Misty So sorry you all skip the workshop!

  12. The Lost Ways说道:

    I see something truly special in this internet site.

  13. Must share说道:

    logiciel lire mkv logiciel amplificateur wifi

  14. Nwokolo说道:

    Spot on with this write-up, I seriously feel this web site needs a great deal more attention. I all probably be back again to see more, thanks for the info!

  15. There as certainly a lot to learn about this issue. I really like all the points you ave made.

  16. son chong tham说道:

    Very neat blog.Thanks Again. Really Cool. here

  17. Really informative article. Much obliged.

  18. There is noticeably a bundle to learn about this. I assume you made sure nice points in features also.

  19. Very informative article post.Thanks Again. Great.

  20. Normally I do not learn article on blogs, however I wish to say that this write-up very compelled me to take a look at and do so! Your writing style has been amazed me. Thanks, quite great article.

  21. Would you be interested in trading links or maybe guest writing a blog post or vice-versa?

  22. Elena Matei说道:

    Im obliged for the blog.Really looking forward to read more. Keep writing.

  23. fashion说道:

    Thanks for sharing, this is a fantastic article.Thanks Again. Great.

  24. Thank you for helping out, excellent info.

  25. Thanks again for the blog post.Really thank you! Fantastic.

  26. Blogger SEO说道:

    Thanks for sharing, this is a fantastic article.Thanks Again.

  27. Your home is valueble for me. Thanks!aаАа’б‚Т€ТšаЂаŒаАТ’аЂа†

  28. Some truly choice posts on this site, saved to my bookmarks.

  29. Sisimiut说道:

    really excellent post, i undoubtedly actually like this incredible web-site, go on it

  30. more说道:

    You have remarked very interesting details ! ps decent site. I didn at attend the funeral, but I sent a nice letter saying that I approved of it. by Mark Twain.

  31. You have a number of truly of the essence in a row printed at this point. Excellent job and keep reorganization superb stuff.

  32. I’а†ve recently started a blog, the info you offer on this site has helped me greatly. Thank you for all of your time & work.

  33. School news说道:

    Thanks so much for the blog.Much thanks again. Want more.

  34. Then you all know which is right for you.

  35. This site was how do I say it? Relevant!! Finally I have found something that helped me. Thanks!

  36. to learn more说道:

    provide credit and sources back to your site? My website is in the very same niche as

  37. click here说道:

    This web site certainly has all of the info I wanted about this subject and didn at know who to ask.

  38. Really appreciate you sharing this article.Really looking forward to read more. Want more.

  39. Your style is so unique compared to other people I have read stuff from. Thanks for posting when you ave got the opportunity, Guess I will just book mark this page.

  40. I will regularly upload tons of stock imagery but I?m not sure what to do about the copyright issue? please help!.. Thanks!.

  41. There is obviously a bunch to realize about this. I suppose you made certain good points in features also.

  42. Perfect work you have done, this site is really cool with good information.

  43. This web site certainly has all of the information and facts I wanted about this subject and didn at know who to ask.

  44. Really enjoyed this article.Really looking forward to read more. Really Cool.

  45. travel说道:

    Please let me know if you are looking for a article author for

  46. Very good post. I absolutely love this site. Continue the good work!

  47. Thank you for your blog article.Thanks Again. Much obliged.

  48. you modify it yourself? Either way stay up the nice quality writing, it is

  49. There as certainly a lot to know about this topic. I really like all of the points you have made.

  50. check out说道:

    Why people still make use of to read news papers when in this technological world everything is available on web?

  51. Your style is very unique in comparison to other people I ave read stuff from. I appreciate you for posting when you ave got the opportunity, Guess I all just bookmark this page.

  52. this website说道:

    Very informative blog post. Keep writing.

  53. There is apparently a lot to know about this. I consider you made various good points in features also.

  54. Really enjoyed this article.Thanks Again. Keep writing.

  55. Very neat blog post.Thanks Again. Much obliged.

  56. wow, awesome blog article.Thanks Again. Really Great.

  57. ndu说道:

    It as not that I want to copy your website, excluding I especially like the layout. Possibly will you discern me which propose are you using? Or was it custom made?

  58. go to说道:

    Major thankies for the blog article.Much thanks again. Really Cool.

  59. My brother suggested I might like this website. He was totally right. This post actually made my day. You cann at imagine just how much time I had spent for this info! Thanks!

  60. caratulas CD说道:

    You created various good points there. I did a search on the topic and discovered a lot of people will have the same opinion together with your weblog.

  61. visit说道:

    Thank you for your blog post.Really thank you! Want more.

  62. You are my inspiration , I have few blogs and infrequently run out from to brand.

  63. mua launchpad说道:

    Simply a smiling visitor here to share the love (:, btw outstanding design. аЂа‹аЂ Audacity, more audacity and always audacity.аЂ аЂа› by Georges Jacques Danton.

  64. Looking forward to reading more. Great blog post.Thanks Again. Will read on

  65. genuine parts说道:

    Really appreciate you sharing this article post.Thanks Again. Really Cool.

  66. check here说道:

    This is one awesome blog.Really thank you! Really Cool.

  67. There as noticeably a bundle to find out about this. I assume you made sure good points in features also.

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>