When using Cloudflare as a reverse proxy, the actual IP addresses of visitors to your website are replaced with Cloudflare's IP addresses. However, Cloudflare includes the original visitor IP address in the HTTP headers, making it possible to retrieve the real IP address of your users.
Here’s how you can access the real IP address of users when your website is behind Cloudflare, particularly if you’re using shared web hosting:
1. Using CF-Connecting-IP HTTP Header:
This header is specifically added by Cloudflare to all requests forwarded to your server and contains the original visitor's IP address. You can access this header to get the real IP address.
For PHP:
If your website is running on PHP, as is common with many shared hosting environments, you can access this header with the following code:
if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) {
$userIP = $_SERVER["HTTP_CF_CONNECTING_IP"];
} else {
$userIP = $_SERVER['REMOTE_ADDR'];
}
Here, $userIP will have the real IP address of the user. The fallback to $_SERVER['REMOTE_ADDR'] is for environments where Cloudflare is not configured or active.
For Other Programming Languages:
-
Node.js (using Express.js):
let userIP = req.headers['cf-connecting-ip'] || req.ip;
-
Python (using Flask):
userIP = request.headers.get('CF-Connecting-IP') or request.remote_addr
-
Ruby on Rails:
user_ip = request.headers["CF-Connecting-IP"] || request.remote_ip
2. Configuring Server or Using Plugins:
Depending on your shared hosting setup and the server software, there might be configurations or plugins/modules that automatically translate Cloudflare headers into the expected IP address fields.
Apache:
For Apache servers, you can use mod_remoteip if it's enabled on your shared hosting (you might need to check with your hosting provider). This module lets Apache httpd use the user's real IP address in place of the Cloudflare IPs.
Add these lines to your .htaccess file (make sure your host permits these directives):
RemoteIPHeader CF-Connecting-IP
Nginx:
For Nginx, the real IP module (ngx_http_realip_module) can be configured to use the Cloudflare header. You would typically add a configuration like this in your Nginx configuration file:
set_real_ip_from 103.21.244.0/22;
real_ip_header CF-Connecting-IP;
(Assuming your host allows you to modify these settings, which might not often be the case with shared hosting.)
3. Contacting Support:
If you're unsure how to proceed or lack the permissions needed to make these changes, you can always reach out to your hosting provider's support team. They can offer guidance specific to their setup, and in some cases, they might set up everything for you.
Final Note:
Always be wary of relying solely on HTTP headers for security-sensitive operations, as headers can be spoofed. In the context of Cloudflare and a properly configured server, however, CF-Connecting-IP should be reliable. Use it alongside other security measures to ensure your application's integrity and security.