I've found an example of doing log rotation in Nginx here

But a simple test with: set $date "2018-08-24"; access_log /home/tim/log/access-http-$date.log default;

produces a log file named access-http-.log. I'm using nginx 1.13.6 (with openresty).

Update

After much hacking & tweaking, I've come up with the following logrotate script to rotate the different log files that nginx produces. I've put it into /etc/logrotate. The remaining issue is that the logs don't rotate daily (I'm unsure why at present), but a logrotate -f <filename> produces exactly the result I want.

An interesting note is that nginx -s reload can be used instead of USR1. That's unfortunately not referenced in the nginx logging page but I found it (in the man page IIRC). I build openresty/nginx manually to incorporate extra modules I need so I don't get various extras that come in the packaged version like the pid keeping.

/path/to/log/access-http.log /path/to/log/access-https.log /path/to/log/api.log /path/to/log/error.log {
    daily
    missingok
    notifempty
    create 664 nobody tim
    dateext
    dateformat -%Y-%m-%d
    dateyesterday
    rotate 10
    su tim tim
    postrotate
      /usr/local/bin/openresty -s reload
    endscript

}

I figure this will be useful for anyone with a large nginx config serving both web pages and an API. I keep the http separate as I don't serve non-https pages and it keeps the script kiddie crap out of my page logs.

  • Have you tried actually doing what is documented in that tutorial? – Michael Hampton Aug 24 at 1:46
  • I've tried the command that sets the $year, $month and $day variables. And then tried access_log /home/tim/log/access-$year.log; Same log file name . – timbo Aug 24 at 1:50
  • I can only confirm that your simple test pasted above, works in my setup – Krzysztof Księżyk Sep 12 at 9:23

Just set a cron task for a minute to midnight to move the logfile and rename it with the date and then send a USR1 signal to Nginx. This will trigger it to reopen log files and create a new one for the following day.

59 23 * * * mv /var/log/nginx/access.log /var/log/nginx/$(date +%F).access.log && kill -USR1 $(cat /run/nginx.pid)
  • why not to use logrotate for this? – Krzysztof Księżyk Sep 12 at 9:06
  • Because I can do it in a single line of bash – miknik Sep 12 at 10:35

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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