[LNMP] Nginx access_log Daily Rotation

Previously, I had a service using Nginx as a reverse proxy. Due to the high volume of traffic, I wanted to do some simple access statistics at the Nginx layer. I found that Nginx’s default access_log writes everything to a single file, which is very inconvenient. After some research, many people suggested using shell scripts to solve this problem. Finally, I found a better solution – Nginx supports the following configuration:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
server {
    listen       8082;
    server_name  your ip;

    if ($time_iso8601 ~ "^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})"){
        set $year \$1;
        set $month \$2;
        set $day \$3;
        set $hour \$4;
        set $minutes \$5;
        set $seconds \$6;
    }

    access_log logs/8082_$year-$month-$day.log;
    error_log logs/8082.error;

    # Forward all requests
    location / {
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass http://localhost:8082;
    }
}