How to setup modsecurity to determine client IP-address correctly, if Nginx webserver…
- User
How to setup modsecurity to determine client IP-address correctly, if Nginx webserver placed behind firewall NAT ?
- Assistant
How to setup modsecurity to determine client IP-address correctly, if Nginx webserver placed behind firewall NAT ?
When you have Nginx behind a firewall or NAT and using ModSecurity (typically via ModSecurity-nginx connector or similar setup), determining the correct client IP can be tricky since the webserver sees the firewall’s IP as the client IP, not the original client IP.
X-Forwarded-For header or a similar customized header.X-Forwarded-For header (or a similar header like X-Real-IP).X-Forwarded-For: 203.0.113.45
Use the official ngx_http_realip_module:
http {
# Trust the firewall IP since it is a trusted proxy
set_real_ip_from 192.0.2.1; # Replace with your firewall IP address
# Use X-Forwarded-For header to get the original client IP
real_ip_header X-Forwarded-For;
# (Optional) Use the first IP in X-Forwarded-For if multiple IPs exist:
real_ip_recursive on;
...
}
set_real_ip_from is the trusted IP of your firewall.real_ip_header specifies the header containing the real client IP.real_ip_recursive on means Nginx will use the first non-trusted IP in the X-Forwarded-For chain.Add a debug log or use:
log_format custom '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';
access_log /var/log/nginx/access.log custom;
The $remote_addr should now be the original client IP.
$remote_addr (or equivalent in connector) for the client IP.$remote_addr is corrected by realip module).If you want to explicitly use the X-Forwarded-For inside ModSecurity, you can reference it via REQUEST_HEADERS:X-Forwarded-For, but normally this is not recommended since X-Forwarded-For can be spoofed unless coming from trusted proxy only.
To set the client IP for ModSecurity via rule (only if critical):
SecRule REQUEST_HEADERS:X-Forwarded-For "^([0-9\.]+)" \
"phase:1,pass,id:1000,nolog,ctl:ip=%1"
But only use this if and only if you trust the incoming header (e.g., after realip module processed it).
| Step | Configuration Location | Notes |
|---|---|---|
Set X-Forwarded-For in firewall | Firewall/NAT | Must add original client IP |
| Trust firewall IP (proxy) | Nginx | set_real_ip_from |
| Use header for real IP | Nginx | real_ip_header X-Forwarded-For and real_ip_recursive on |
| Verify client IP in logs | Nginx | Check $remote_addr |
| ModSecurity client IP | ModSecurity (NGINX inherits $remote_addr) | Normally automatic |
http {
set_real_ip_from 192.168.1.1; # Firewall IP address
real_ip_header X-Forwarded-For;
real_ip_recursive on;
# ModSecurity config (load module and configuration files here)
# ...
}
If you configure your firewall correctly and Nginx properly trusts it, ModSecurity will automatically process and log the correct client IP.
Not yet included in a published release.