Forward requesting IP from Nginx to Apache's logs

5,543

Solution 1

you need to change apache's log format to support x-forward

for example

LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %{X-Forwarded-For}i" combined

Then you can use

 CustomLog logs/access_log combined

So the last entry in your log will be the header nginx is setting for the real IP. Of course you can switch around the order in the LogFormat line

Solution 2

Have a look at the mod_rpaf apache module

On deb/ubuntu you can install package name libapache2-mod-rpaf

Once installed, add your nginx IP to the RPAFproxy_ips setting in /etc/apache2/mods-available/rpaf.conf

<IfModule mod_rpaf.c>
RPAFenable On RPAFsethostname 
On RPAFproxy_ips 127.0.0.1   
</IfModule>

Restart apache & you should see the correct IP addresses in your logs.

I'd keep this in place in your nginx config as well:

proxy_set_header Host $host;
proxy_set_header X-Real-IP  $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
Share:
5,543

Related videos on Youtube

diomonogatari
Author by

diomonogatari

Updated on September 18, 2022

Comments

  • diomonogatari
    diomonogatari over 1 year

    I'm using nginx as a front end reverse proxy for Apache, I have the following configuration inside of nginx:

    location / {
      if (-f $request_filename) {
          add_header X-Static hit;
          access_log off;
        }
    
      if (!-f $request_filename) {
          proxy_pass https://127.0.0.1:8000;
          add_header X-Static miss;
        }
    

    With apache listening on port 8000 locally. When I look at apache's logs all the requests come from 127.0.0.1:443 (which is where nginx is sitting). I want to forward the real IP to apache so that it stores it properly in the logs.

    I tried adding the following lines to the location block to no avail

    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    

    Am I missing a step here? Do I need to change apache's log format? It is currently using the default combined log.

    • kolbyjack
      kolbyjack over 12 years
      Just a suggestion, but your config would be a bit cleaner without the ifs (assuming you're on 0.7+): location / { add_header X-Static hit; access_log off; try_files $uri @apache; } location @apache { add_header X-Static miss; proxy_pass 127.0.0.1:8000; }
  • symcbean
    symcbean over 4 years
    THIS IS WRONG. X-Forwarded for can be multi-valued - each proxy in a chain should add the client address it sees. If you are trying to add the information in a new column then it should be delimited using quotes or brackets. If you want a single value for the client address, use X-Real-IP. developer.mozilla.org/en-US/docs/Web/HTTP/Headers/…