Nginx: How to replicate Apache’s other_vhosts_access.log file to get vhost at start of log line

debianloggingnginxUbuntuvirtualhost

I have multiple sites hosted on a server running Nginx. I don't want to use separate log files for all my vhosts, but I do want to be able to tell from the logs which Nginx vhost each request belonged to. This is not possible with the default NCSA "combined" format used by /var/log/nginx/access.log .

Apache under Debian/Ubuntu logs to /var/log/apache2/other_vhosts_access.log by default, which does include the vhost name. How do I replicate this for Nginx?

Best Answer

Save the following snippet as /etc/nginx/other-vhosts-access-log.conf and reload Nginx. This will start logging to /var/log/nginx/other_vhosts_access.log. (This will not stop logging to /var/log/nginx/access.log .) The format is the same (NCSA "combined" format) but with the value of server_name at the start of the line. Note that the vhost's name is used, which is not necessarily the same as the requested hostname (if there are additional server_name directives for aliases).

# borrowed from Apache
# (Could use $host instead of $server_name to log vhost aliases separately)
log_format vhost_combined '$server_name $remote_addr - $remote_user [$time_local] '
                          '"$request" $status $body_bytes_sent '
                          '"$http_referer" "$http_user_agent"';

# Define an access log for VirtualHosts that don't define their own logfile
access_log /var/log/nginx/other_vhosts_access.log vhost_combined

(Watch out for log rotation, but this should be covered for all files in /var/log/nginx by the nginx-full package's logrotate file.)

Warning: Don't try to disable logging to /var/log/nginx/access.log by using access_log off; before the above, as this will prevent subsequent access_log statements from working.