Get the real client IP address, when you use a reverse proxy

Let’s say you are running ASP.NET, PHP, JSP, or Python web. If the code is visited via reverse proxy, then the client IP address is the proxy IP with regular detecting routue. To fix the issue, let’s first take a look at 3 HTTP headers added by proxies:

The IP address(s) of the client. If there are multiple proxies, you see multiple IP addresses, separated by comma. For example:

X-Forwarded-For: client1, proxy1, proxy2

The original host requested by the client in the Host HTTP request header.

The hostname of the proxy server.


The Solution:

It’s pretty straightforward. The flow is:

  1. Check if there is X-Forwarded-For in http headers.
  2. If yes, get the string, and split it by comma. Then get the first piece.
  3. If no, fall back on regular way of reading IP address.

That’s it.

This entry was posted in Server, Web and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *


This site uses Akismet to reduce spam. Learn how your comment data is processed.