Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get real ip address of a request instead of Cloudflare's ip address

Cloudflare changes the IP addresses of incomming requests because Cloudflare is a middleware between my website and the Internet, a proxy.

How should I get the initial IP address of the request, not Cloudflare its IP address. I heard about the mod_cloudflare but does this plugin only updates the IP address in my logs (?) And I didn't find a version for Nginx.

like image 355
Michiel Avatar asked Aug 26 '18 13:08

Michiel


2 Answers

Are you using express? If so you can use the cloudflare-express middleware package to retrieve the IP addresses you need.

var cloudflare = require('cloudflare-express');
...
var express = require('express');
var app = express();
...
app.use(cloudflare.restore({update_on_start:true}));

Then the user's original address appears on req objects as cf_ip.

You may also, if your express app is behind a typical nginx reverse proxy, use express's trust proxy setting.

For example:

    app.set( 'trust proxy', 'loopback' ); //trust localhost reverse proxy

Other request-processing frameworks most likely have their own packages to do similar things.

like image 169
O. Jones Avatar answered Sep 21 '22 03:09

O. Jones


Cloudflare sets the CF-Connecting-IP and the X-Forwarded-For headers on every request

You can simply get the IP from their special header:

let ip = req.headers['cf-connecting-ip']

If you expect requests outside of Cloudflare, you can get these IPs the following way:

let otherIp = req.headers['x-forwarded-for'] || req.connection.remoteAddress

Though, be wary, that other Proxies (like Nginx) will also set the x-forwarded-for header.

like image 28
Luca Kiebel Avatar answered Sep 21 '22 03:09

Luca Kiebel