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).


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 {
    create 664 nobody tim
    dateformat -%Y-%m-%d
    rotate 10
    su tim tim
      /usr/local/bin/openresty -s reload


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 '18 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 '18 at 1:50
  • I can only confirm that your simple test pasted above, works in my setup – Krzysztof Księżyk Sep 12 '18 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)
| improve this answer | |
  • 1
    why not to use logrotate for this? – Krzysztof Księżyk Sep 12 '18 at 9:06
  • Because I can do it in a single line of bash – miknik Sep 12 '18 at 10:35
  • but then you cannot ask that one line of code to save only 14 days of historic logs, supposing that this feature is wanted. – Kid_Learning_C Feb 21 at 6:49
  • True. I'll need a second line of code to delete the log files which are more than 14 days old. – miknik Feb 21 at 18:56

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.