How to retrieve the connecting clients real IP in Nginx
This module is not built by default in the Nginx build distributed in the Debian repository, or by default when compiling your own. The Real IP module can be enabled in Nginx by either compiling the module manually or by installing a build with the module compiled by default.
Installation
There are multiple ways to install a version of nginx compiled with support for ngx_http_realip_module
. For many distributions third party or official repositories may include a package with support.
Installation from the Dotdeb repository on Debian and Ubuntu
The easiest way would be to install Nginx with this module is via the Dotdeb repository on Debian. To do this you'll need to add the Dotdeb repository, to your package manager. Instructions for installing the repository can be found on the official Dotdeb website. After installation of the Dotdeb Repository you can begin the installation of their Nginx package.
Steps to perform (as root):
- First uninstall any existing nginx package you may have installed.
apt-get remove nginx*
- Perform an update on the local cache of packages if you have not already.
apt-get update
- Install nginx from the Dotdeb repository
apt-get install nginx -y
Installation from source
The ngx_http_realip_module
module is not built by default, it should be enabled with the --with-http_realip_module
configuration parameter.
Steps to perform (as root):
- Download the latest version of nginx from the Nginx project home page.
wget http://nginx.org/download/nginx-1.7.4.tar.gz
- Extract the source files from the compressed archive
tar -zxvf nginx-1.7.4.tar.gz
- After extracting the source, run these commands to compile nginx:
./configure --with-http_realip_module
make
sudo make install
Configuration
- First verify that Nginx has been installed installed with the
ngx_realip
module enabled. You can confirm that this module is enabled by checking the output ofnginx -V
configure arguments: [...] --with-http_realip_module [...]
- In your
nginx.conf
file (which can usually be found in/etc/nginx/nginx.conf
) in the http block, or in the server block for your website add:
set_real_ip_from x.x.x.x; #x.x.x.x is your proxy IP
real_ip_header X-Real-IP;
- You can verify the syntax of your configuration at any time by executing
nginx -t
More Information
Information on the X-Real-IP header can be found here. Specifics on the Nginx web server can be found on the project website and documentation for the ngx_http_realip_module.