Bambinos RSS

New Bamboo

Bamboo Blog

Archive

Nov
12th
Wed
permalink bartoszblimke

How to get remote_ip address in Rails application behind proxy.

To get the ip address of a client in rails application, you can call remote_ip method on request object. This works fine, unless your application is behind proxy which ip address doesn’t match the following regular expression:

    
    /^127\.0\.0\.1$|^(10|172\.(1[6-9]|2[0-9]|30|31)|192\.168)\./
    

If the proxy ip address is different, remote_ip will return ip address of the proxy. To fix this problem, you have to change the regular expression to match your proxy ip address and overwrite TRUSTED_PROXIES constant in AbstractRequest class in one of the application initializers. For example, if your proxy ip address is 201.202.203.204, you could use the following code:

    
    ActionController::AbstractRequest.const_set("TRUSTED_PROXIES", /^201\.202\.203\.204$|^127\.0\.0\.1$|^(10|172\.(1[6-9]|2[0-9]|30|31)|192\.168)\./i)