Blog
SavedSearch
Visit Hostlelo

Rotate Apache and Nginx Logs With logrotate, Safely

A logrotate rule without a reload step leaves your web server writing to the old file. Write, test and verify a safe rule for Apache or Nginx, plus WHM options.

The short answer

A safe logrotate rule for a web server needs a postrotate step that makes the server reopen its logs: nginx -s reopen (the USR1 signal) for Nginx, or a graceful restart such as apachectl graceful for Apache. Without it the server keeps writing to the renamed file. Add a rotate count, because logrotate's default count of 0 removes old versions, and use delaycompress for Apache because a graceful restart does not close old log files immediately. Test with logrotate -d, which changes nothing, before forcing one rotation with -f.

Web server log files rotating into compressed archives with configuration validation and a rollback path
Reading options

On this page

Before you start

Root or sudo SSH access; confirmed web-server log and PID paths; an existing logrotate rule inventory; a maintenance window; a private backup of the rule; permission to test a single rotation.

To rotate Apache or Nginx logs safely with logrotate, you need two things in the rule: the rotation itself and a step that tells the web server to reopen its log files. Without that second step the rotation looks fine on paper, but the server goes on writing somewhere you did not expect.

Here is the part that catches people. When logrotate renames access.log to access.log.1, the web server does not notice. The Apache documentation says it plainly: httpd keeps writing to the old file handle until it receives a signal. So your fresh access.log sits at zero bytes, the "old" file keeps growing, and your retention limits stop meaning anything while the disk slowly fills.

By the end of this guide you will be able to write a logrotate rule for Nginx or Apache on a VPS, test it without touching a single log, force one real rotation, and confirm it worked. If you run a cPanel server, you will also know which WHM screens control log rotation there.

What log rotation actually is

Log rotation means closing off the current log file, setting it aside under a new name, starting a fresh one, and deleting the oldest copies after a while. It keeps logs useful and stops them eating the disk. The Apache docs note that the access log typically grows 1 MB or more per 10,000 requests, so a busy site can produce a lot.

Think of a shop assistant writing every sale in a notebook. You take the full notebook away and put a new one on the counter. But the assistant is focused and keeps writing in the old notebook, which is now in your back office, until you tap them on the shoulder and say "use the new one". In log rotation, that shoulder tap is a signal or reload sent to the web server. The postrotate block in a logrotate rule is where the tap goes.

Quick tip: logrotate is a small Linux tool that rotates, compresses and deletes old logs on a schedule. Its man page says it normally runs as a daily cron job, or through logrotate.timer on systems that use systemd.

Before you start

  • Root or sudo access to the server over SSH. If you are new to servers, what web hosting is gives useful background.
  • The exact paths of your web server's log files. These vary by distribution and by your own configuration, so do not guess.
  • A copy of any logrotate file you plan to edit, kept outside /etc/logrotate.d/.
  • About 20 minutes, plus a second look the next day after the scheduled run.
  • Risk level: low if you test first. The real risks are deleting logs you wanted to keep, or a reload step that fails and leaves the server writing to the old file.
  • If the server runs cPanel and WHM, skip ahead to the cPanel section before you write any rule. cPanel has its own log handling.

Heads up: the commands in this guide that are not quoted from official docs are illustrative. Read each one, check the paths match your server, and only then run it.

Write a logrotate rule for Nginx

Nginx makes this fairly easy. Its control documentation describes exactly what to do: rename the log files first, then send the USR1 signal to the master process. The master reopens all open log files, then tells the worker processes to do the same, and the old files are almost immediately free for compression.

Step 1: Find your log paths and any existing rule

Your logs are wherever the access_log and error_log directives in your Nginx configuration point. The -T flag, documented on the Nginx command-line page, tests the configuration and prints it in full. The command below pipes that output through grep to show only the log lines (illustrative).

sudo nginx -T 2>/dev/null | grep -E "access_log|error_log"

You should see lines like access_log /var/log/nginx/access.log;. Write down every distinct path.

Next, check whether a rule for those files already exists. A package may already have installed one, and the Apache docs suggest checking /etc/logrotate.d/ for exactly this reason. This command lists the folder and searches it for your log path (illustrative).

ls -l /etc/logrotate.d/
sudo grep -rl "/var/log/nginx" /etc/logrotate.d/

If a file comes back, edit that file instead of adding a second rule for the same logs.

Step 2: Back up the configuration file

Copy any file you will touch to a private directory with a UTC timestamp in the name. The timestamp includes seconds, so a second run cannot silently replace the first backup. This example backs up an existing Nginx rule (illustrative; change the file name to match yours).

sudo sh -c 'umask 077; install -d -m 700 /root/logrotate-backup; stamp=$(date -u +%Y%m%dT%H%M%SZ); cp -a -- /etc/logrotate.d/nginx "/root/logrotate-backup/nginx.$stamp"; test -s "/root/logrotate-backup/nginx.$stamp"'

Keep the backup outside /etc/logrotate.d/. If your main /etc/logrotate.conf has an include line for that folder, which you can check with grep include /etc/logrotate.conf, a backup left inside it becomes a live rule.

Step 3: Write the rule

Here is a rule for every .log file in /var/log/nginx/. It rotates daily, keeps 14 old copies, compresses them, and tells Nginx to reopen its logs once after rotation. Save it as /etc/logrotate.d/nginx, or edit the existing file to match.

/var/log/nginx/*.log {
    daily
    rotate 14
    missingok
    notifempty
    compress
    delaycompress
    sharedscripts
    postrotate
        /usr/sbin/nginx -t && /usr/sbin/nginx -s reopen
    endscript
}

Here is what each line does, in plain words, all taken from the logrotate man page.

  • daily rotates once a day. You can use weekly or monthly instead.
  • rotate 14 keeps 14 old versions before deleting the oldest.
  • missingok skips a missing log without an error.
  • notifempty does not rotate an empty log.
  • compress gzips old copies. delaycompress waits one extra cycle before compressing the newest old copy.
  • sharedscripts runs the postrotate script once for the whole pattern, not once per file.
  • postrotate to endscript is the shoulder tap. It runs after the files are renamed and before the old copy is compressed.

The nginx -s reopen command is documented by Nginx as "reopen log files". The rule first runs nginx -t, so a broken configuration stops the reopen command. Confirm the binary path with command -v nginx; replace /usr/sbin/nginx in the rule if your package uses another path.

If you prefer the USR1 signal directly, first find the configured pid file with nginx -T, verify that it is non-empty, and confirm the process belongs to the Nginx master before signalling it. This illustrative sequence does those checks without guessing a PID:

sudo test -s /run/nginx.pid
ps -p "$(sudo cat /run/nginx.pid)" -o pid=,comm=,args=
# Run only after the output identifies the expected Nginx master process:
sudo kill -USR1 "$(sudo cat /run/nginx.pid)"

Why this matters: the rotate line is not optional. The man page says the default count is 0, and with 0 old versions are removed rather than kept. Forget that line and your "rotation" becomes "delete yesterday's log".

Step 4: Dry run with debug mode

Now test without changing anything. The -d flag turns on debug mode, which the man page says makes no changes to the logs and does not update the state file. This command runs the main configuration in debug mode so your rule is read with the same global settings it will get at night.

sudo logrotate -d /etc/logrotate.conf

Scroll to the part that mentions your Nginx files. You should see each log considered and whether it needs rotating. If it says a log does not need rotating yet, that is normal on the first day.

Step 5: Force one real rotation

Once the dry run looks right, do one real rotation so you can watch it happen. The -f flag forces rotation even if logrotate thinks it is not due, and -v prints what it is doing. Pass just your rule file so other logs on the server are left alone.

sudo logrotate -v -f /etc/logrotate.d/nginx

Heads up: when you pass one file directly, global settings from /etc/logrotate.conf do not come along, because that file is not on the command line. That is why the rule above spells out every option it needs.

You should now see access.log.1 next to a fresh access.log. Move on to the checks section to confirm the new file is the one being written.

Write a logrotate rule for Apache

The idea is the same, with one important difference. Apache's tap on the shoulder is a graceful restart, and graceful means it lets busy processes finish their current requests first.

Step 1: Find paths and back up

Apache logs are wherever your CustomLog and ErrorLog directives point. The directory and the service name differ between distributions, so check your own configuration. Then back up any existing rule exactly as in the Nginx section, copying it to /root/logrotate-backup/ with a date on the end.

Step 2: Write the rule

The Apache documentation says the standard approach is a graceful restart in the postrotate script, using /usr/sbin/apachectl graceful or the equivalent systemctl reload command. This example rule rotates every .log file in an example Apache log folder. Adjust the path to match yours.

/var/log/apache2/*.log {
    weekly
    rotate 8
    missingok
    notifempty
    compress
    delaycompress
    sharedscripts
    postrotate
        /usr/sbin/apachectl configtest && /usr/sbin/apachectl graceful
    endscript
}

Check that /usr/sbin/apachectl exists on your server first, with ls -l /usr/sbin/apachectl. If it does not, use the reload command for your Apache service instead. The service name varies by distribution, so confirm it with systemctl list-units | grep -i -E "apache|httpd" (illustrative).

Step 3: Understand why delaycompress matters more for Apache

The apachectl page says a graceful restart does not abort open connections, and a side effect is that old log files are not closed immediately. The Apache page on stopping and restarting goes further. It says there is no way for a rotation script using a graceful restart to know for certain that all the old processes have finished writing. It suggests waiting, for example 15 minutes if most requests finish within 10.

So for a few minutes after rotation, some Apache processes may still write to access.log.1. If logrotate compressed that file straight away, those late lines would go into a file that has already been replaced by its .gz copy. The delaycompress option fixes this neatly. The man page says it postpones compression of the previous log to the next rotation cycle, and exists for programs that may keep writing to the previous file for some time.

Here is a made-up example: a small shop runs a weekly rule with compress but no delaycompress. Every Sunday night the gzip runs while old processes are still logging slow downloads. Months later, someone checking a payment dispute finds a gap in Sunday's log. Adding delaycompress gives those processes a full week to finish instead of a few seconds.

Step 4: Test the same way

These are the same two commands as before, pointed at your Apache rule.

sudo logrotate -d /etc/logrotate.conf
sudo logrotate -v -f /etc/logrotate.d/apache2

The Apache docs say a graceful restart runs a syntax check first and refuses to restart on an error. So run apachectl configtest beforehand, which reports Syntax Ok when the configuration parses, especially if you edited Apache recently, for example while checking TLS 1.3.

The alternative: rotatelogs

Apache also ships its own rotation program, rotatelogs, which works through piped logs. Apache writes each log line into a pipe, and rotatelogs writes it to disk and switches files on a time or size limit. The Apache logs page calls this the simplest approach, because it rotates without a server restart.

This example from the Apache docs rotates the access log every 24 hours. The rotatelogs path depends on your install.

CustomLog "|/usr/local/apache/bin/rotatelogs /var/log/httpd/access_log 86400" combined

Pick one tool per log: never point a logrotate rule at files rotatelogs manages. Read its -n option, which keeps a fixed number of files in a circle, and plan cleanup of old files before you switch.

What about copytruncate?

You will see copytruncate in many rules online. Instead of renaming the log, it copies it and then empties the original in place, so the program never needs to reopen anything.

For programs that cannot be told to reopen their logs, that is the only choice. But the man page warns there is a very small time slice between copying and truncating, so some logging data might be lost. Apache and Nginx can both reopen their logs, so use the reload step instead.

On a cPanel server: use WHM

On a server running cPanel and WHM, cPanel's own daemon, cpanellogd, compresses and archives the Apache logs you select in WHM. I could not find cPanel documentation on how it interacts with custom logrotate rules, so my advice is simple: do not write your own rule for files cPanel manages. Use the WHM screens below, and if you need something they cannot do, ask cPanel support or your host first.

The details below come from cPanel's documentation at the time of writing (21 November 2026). The Log Rotation page is marked valid for version 82 onward, and the Tweak Settings page for version 126 onward.

Choose which Apache logs to archive

Go to WHM > Service Configuration > Apache Configuration > Log Rotation. This screen lets you select Apache log files for cpanellogd to compress and archive. The files listed include error_log, access_log, modsec_debug_log and suexec_log. Tick the ones you want and click Save.

The docs say archiving happens either when a log grows past the rotation size threshold or at the end of the month.

Set the size threshold and retention

Go to WHM > Server Configuration > Tweak Settings and open the Stats and Logs section. These are the settings that matter most for disk space, with their documented defaults.

  • Log rotation size threshold: 300 MB by default. Enter 10 or more. The docs say it does not apply to Apache domlogs, the per-domain access logs.
  • Delete each domain's access logs after statistics are gathered: On by default. This keeps per-domain logs from piling up.
  • Archive logs in the user's home directory at the end of each stats run: On by default.
  • Remove the previous month's archived logs from the user's home directory at the end of each month: On by default.
  • Keep log files at the end of the month: Off by default. The docs strongly recommend leaving it off, because logs can use disk space quickly.
  • Number of days to retain web server logs before purging them: 0 by default, which keeps them indefinitely. Other values run from 3 to 999.

Why this matters: that last default keeps web server logs forever unless you change it.

Quick tip: take a screenshot of the Stats and Logs section before you change anything. That is your backup for WHM settings.

How to check it worked

Run these checks right after your forced rotation, and again the day after the scheduled run.

First, list the log folder with sizes and times. The command below is illustrative, so change the path to your own.

ls -lh --time-style=+%H:%M /var/log/nginx/

You should see a fresh access.log and an access.log.1. Then make a few requests to your site, for example by loading the homepage in a browser, and run the command again. Expected result: access.log has grown and its time has changed, while access.log.1 has stopped changing.

If it is the other way round, the reload step did not work. See the first troubleshooting item below.

Second, check the next day that compression is happening. With delaycompress you should see access.log.1 uncompressed and access.log.2.gz compressed, and so on up to your rotate count.

Third, check the state file. The man page says the default is /var/lib/logrotate.status. Your log paths should appear in it with the date of the last rotation.

sudo grep nginx /var/lib/logrotate.status

If you run fail2ban with a jail that watches web logs, confirm it is still reading the live file after rotation.

Troubleshooting

The new log stays empty while the old one keeps growing

Symptom: access.log is 0 bytes, and access.log.1 keeps getting bigger. Cause: the reload step is missing, or it ran and failed. Fix: run the command from your postrotate block by hand, for example sudo nginx -s reopen or sudo /usr/sbin/apachectl graceful, and read any error it prints. Correct the path or service name in the rule, then force one rotation again.

Old logs vanish right after rotation

Symptom: after rotation there is no .1 file at all. Cause: the rule has no rotate line, and the man page gives the default as 0, which removes old versions. Fix: add rotate 14 or whatever count suits you.

The postrotate script never seems to run

Symptom: the dry run shows your files, but nothing reloads. Cause: with sharedscripts, the man page says scripts are not run at all if none of the logs in the pattern need rotating. It also says that if the script exits with an error, the remaining actions for those logs are skipped. Fix: use -f to force a test rotation, and run the script by hand to check its exit status with echo $? straight after (illustrative).

logrotate exits with code 3

Symptom: a manual run stops at once and echo $? prints 3. Cause: the man page says logrotate locks the state file to prevent two runs at once, and exits with value 3 if it cannot get the lock. Another run, often the scheduled one, is still going. Fix: wait for it to finish, then try again.

Apache's compressed logs have gaps

Symptom: lines are missing near rotation time in .gz files. Cause: compression ran before old Apache processes finished writing after the graceful restart. Fix: add delaycompress so the newest old file waits one cycle before compression.

The one message worth forwarding

If someone else runs your server, send them this:

"Hi, could you check log rotation on our web server? Please confirm the logrotate rule for our Apache or Nginx logs has a postrotate step that reloads the server (apachectl graceful for Apache, nginx -s reopen for Nginx), a rotate count so old logs are kept for a set number of days, and delaycompress for Apache. Please test it with logrotate -d first and send me a listing of the log folder after the next scheduled run, so we can see the new log file is the one being written. If it is a cPanel server, please send screenshots of WHM's Log Rotation page and the Stats and Logs section of Tweak Settings instead. Thanks."

A rotation rule is only safe when the web server is told to let go of the old file, so always check where the new lines are landing.

Reader questions

Does logrotate -d change anything?

No. The logrotate man page says debug mode makes no changes to the logs and does not update the state file, so it is safe for testing a new rule.

What happens if I leave out the rotate line?

The man page gives the default rotate count as 0, and with 0 old versions are removed rather than kept. Always set a count such as rotate 14.

Should I use copytruncate for Apache or Nginx?

Usually not. The man page warns that a small gap between copying and truncating can lose log lines, and both Apache and Nginx can be told to reopen their logs instead.

Is nginx -s reopen the same as sending USR1?

Both are documented by Nginx as reopening log files. The -s reopen form saves you from looking up the master process ID in the pid file yourself.

Why use delaycompress with Apache?

Apache documents that a graceful restart does not close old log files immediately, so some processes may still be writing. delaycompress waits until the next rotation cycle before compressing that file.

Where is the default logrotate state file?

The logrotate man page lists /var/lib/logrotate.status as the default. It records when each log was last rotated.

What is the default log rotation size threshold in WHM?

cPanel documents a default of 300 MB, set in the Stats and Logs section of Tweak Settings. The docs say it does not apply to Apache domlogs.

Sources & further reading

  1. logrotate(8) Linux manual page
  2. Apache HTTP Server 2.4: Log Files
  3. Apache HTTP Server 2.4: Stopping and Restarting
  4. Apache HTTP Server 2.4: apachectl
  5. Apache HTTP Server 2.4: rotatelogs
  6. nginx: Controlling nginx
  7. nginx: Command-line parameters
  8. nginx: Module ngx_http_log_module
  9. cPanel docs: WHM Log Rotation
  10. cPanel docs: Tweak Settings, Stats and Logs

What changed

Made configuration backups private and collision-resistant, added Nginx and Apache configuration tests before reopen/reload, required PID identity verification before USR1, and added original article/social media.

Originally published . About our editorial updates.

Your next project deserves a better foundation.

Explore hosting built for your next chapter.

Explore hosting

Find your next answer.

Search published guides and articles.

Ctrl / ⌘ K to open · Esc to close