Thursday, December 16, 2010

See the User's IP Using Lighttpd Behind Cloudflare (Updated with Apigee)

Using Cloudflare to protect your website is a great choice, however, it can break your existing applications because the IP that your server sees is not the user's, it is Cloudflare's. Cloudflare has a module for Apache to rewrite the IP with the correct one (here), but not for lighttpd. The following 3 steps will get your IP rewritten and have your access logs printing out the correct IP for the connecting user.

Step 1: Open your lighttpd.conf file and append "mod_extforward" to the end of the server.modules list.

Step 2:  Paste the following code block anywhere in the file (well at least after the server.modules lines)
$HTTP["remoteip"] == "204.93.240.0/24" {
extforward.forwarder = ( "all" => "trust" )
extforward.headers = ("CF-Connecting-IP")
}

$HTTP["remoteip"] == "204.93.177.0/24" {
extforward.forwarder = ( "all" => "trust" )
extforward.headers = ("CF-Connecting-IP")
}

$HTTP["remoteip"] == "199.27.128.0/21" {
extforward.forwarder = ( "all" => "trust" )
extforward.headers = ("CF-Connecting-IP")
}

$HTTP["remoteip"] == "173.245.48.0/20" {
extforward.forwarder = ( "all" => "trust" )
extforward.headers = ("CF-Connecting-IP")
}

$HTTP["remoteip"] == "103.22.200.0/22" {
extforward.forwarder = ( "all" => "trust" )
extforward.headers = ("CF-Connecting-IP")
}


Step 3: Restart lighttpd and you're good to go!

You should now see the actual user IPs in the access logs and in your applications.

If you want to add Apigee as well:
$HTTP["remoteip"] == "75.101.150.28/32" {
extforward.forwarder = ( "all" => "trust" )
extforward.headers = ("CF-Connecting-IP")
}

$HTTP["remoteip"] == "174.129.236.240/32" {
extforward.forwarder = ( "all" => "trust" )
extforward.headers = ("CF-Connecting-IP")
}

Thanks,
James Hartig

5 comments:

:: Andi :: said...

Your code wouldn't work on my lighttpd installation, I would get "invalid character" for every ">", so I use this code instead, which is actually more efficient:



## Get working IP lookups with CloudFlare
extforward.forwarder = (
"204.93.240.0/24" => "trust",
"204.93.177.0/24" => "trust",
"199.27.128.0/21" => "trust",
"173.245.48.0/20" => "trust"
)
extforward.headers = ("CF-Connecting-IP")

James Hartig said...

What version of Lighttpd do you have?

Ewantoo said...

I had the same problem as Andi, his code worked for me - thanks both of you.

Version was lighttpd/1.4.28

Ewantoo said...
This comment has been removed by the author.
Anonymous said...

Put the mod_extforward line before mod_accesslog if you want to your access logs to show the real IP address (i.e. not CloudFlare's IP).