I'm using the default nginx package on Ubuntu 14.04 server. It is using /etc/nginx/nginx.conf as the main config, and then includes configs from /etc/nginx/conf.d/*.conf and /etc/nginx/sites-enabled/*.

The default nginx config has this directive for logging to the access log

access_log /var/log/nginx/access.log;

I'd like to add the X-Forwarded-For header, so I do this inside of the conf.d folder:

log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                 '$status $body_bytes_sent "$http_referer" '
                 '"$http_user_agent" "$http_x_forwarded_for"';

access_log  /var/log/nginx/access.log  main;

The problem I have is that then I'm getting two records inside my access.log file - one with the header info and another one without.

I know I can overwrite the nginx.conf file itself, but I'd rather avoid it if possible. I would also like to keep using the same log file (access.log).

Is there a way to tell nginx to override the previous directive and simply change the log format without modifying the main nginx.conf file?


1 Answer 1


the answer to your question is NO, you can't override a log_format at any level in nginx and you can't override access_log when in the same level, except switching it off. However, you can achieve what you wanted without changing nginx.conf but you will have to do it at server {} level.

The issue here is that the include of conf.d/* is inside the http {}, which is exactly where the access_log directive is. What you can do without touching nginx.conf is to change whatever server{} you are using (if you didn't setup one you are using the default one located at /etc/nginx/sites-enabled/default). So to achieve the same without changing nginx.conf you should change your file in the conf.d folder to: log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log off;

And then inside your server{} put: access_log /var/log/nginx/access.log main;

That should get you what you wanted at the beginning.

  • Thanks, that works great. Except that there's usually already a main log_format, so that you need to choose another name.
    – Kutzi
    May 27, 2019 at 9:18
  • Thanks, solution still works and helped me to configure bitnami/nginx docker image, without full rewriting of default config. So I can define new logging format (json logging) and apply it to my setup Mar 26, 2021 at 13:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.