Rotate Nginx logs without logrotate

I wanted a quick and easy way to rotate Nginx logs, preferably without having to install and configure extra software.

After some searching I discovered that the access_log directive supports setting variables in the file path. That means if you have a variable with the current date then it can be placed in the path and, when the variable changes, the log path updates and the logs get rotated.

There are a few caveats to using variables in the access_log path though so worth checking the documentation to see if they’re a good fit before using them. For my use case they seemed like a good fit.

Looking at the documentation the most useful looking variable to get the current date from is time_iso8601 which can be used to extract the date (and time if wanted) from.

The solution I ended up with was adding this to the http config:

http {
    # of http config...

    open_log_file_cache max=1000 inactive=30s valid=1m min_uses=1;

    map $time_iso8601 $year_month {
    	default             'date-parse-error';
    	'~^(?<yearmonth>\d{4}-\d{2})'  $yearmonth;

And then updating the access_log directive in the server configs to:

server {
    # of server config...

    access_log /srv/$year_month-access.log;

Unfortunately this doesn’t work for the error_log directive but for my purposes that’s not really an issue.

You need JavaScript enabled to see comments.