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:

X-Forwarded-For
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

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

X-Forwarded-Server
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 *

ERROR: si-captcha.php plugin: GD image support not detected in PHP!

Contact your web host and ask them to enable GD image support for PHP.

ERROR: si-captcha.php plugin: imagepng function not detected in PHP!

Contact your web host and ask them to enable imagepng for PHP.