Log rotation is an important aspect of managing log files on a Linux system, including those generated by Nginx. Logrotate is a utility that helps automate the rotation, compression, removal, and mailing of log files. Here’s a basic guide on how to set up log rotation for Nginx on Ubuntu using logrotate.
Create a Logrotate Configuration File for Nginx:
Open your preferred text editor and create a new logrotate configuration file for Nginx. The convention is to use a separate file for each service. Let’s create a file for Nginx:
sudo nano /etc/logrotate.d/nginx
Inside the file, you can add the following configuration:
create 0640 www-data adm
if [ -d /etc/logrotate.d/httpd-prerotate ]; then \
run-parts /etc/logrotate.d/httpd-prerotate; \
invoke-rc.d nginx rotate >/dev/null 2>&1
daily: Rotates the logs on a weekly basis. You can change to
weeklyif want make dailiy rotation
missingok: Ignores errors if the log file is missing.
rotate 14: Keeps 14 rotated log files.
compress: Compresses the rotated log files using gzip.
delaycompress: Delays compression of the previous log file until the next rotation cycle.
notifempty: Does not rotate the log if it is empty.
create: Sets the permissions and ownership for the new log file.
sharedscripts: Runs the postrotate script only once for all matching files.
postrotate: The script to run after the log files are rotated. In this case, it sends a signal to Nginx to reopen its log files.
Test Log Rotation
You can test log rotation manually by running.
sudo logrotate -d /etc/logrotate.conf
-d option is for debugging, and it will show you what logrotate would do without actually doing it. Once you are satisfied with the output, you can run logrotate without the
-d option to apply the rotation.
sudo logrotate /etc/logrotate.conf
Additionally, you can force log rotation for a specific log file.
sudo logrotate -f /etc/logrotate.d/nginx
Verify Log Rotation
After log rotation, check that the log files have been rotated, compressed, and that Nginx is still able to write to the logs.
By setting up Logrotate Nginx Ubuntu, you ensure that log files are managed efficiently, preventing them from consuming too much disk space and making it easier to analyze historical log data.