Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
FREEDOM251

Freedom251 › Blog › Linux administration

How to Configure Logging and Log Rotation in Nginx on Ubuntu

By Freedom251 Team · · 10 min read

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

On a normal Ubuntu package installation, Nginx reads /etc/nginx/nginx.conf and writes request and diagnostic messages to /var/log/nginx/access.log and /var/log/nginx/error.log. Configure the error_log, log_format, and access_log directives, validate with nginx -t, reload the service, and let Ubuntu’s logrotate rotate and compress the files. The safest rotation method depends on whether the running Nginx process can reopen its log descriptors.

Find the configuration and log paths actually in use

Ubuntu’s packaged Nginx convention is:

  • Configuration: /etc/nginx/nginx.conf
  • Access log: /var/log/nginx/access.log
  • Error log: /var/log/nginx/error.log

Those paths are conventions, not guarantees. An installation from another repository, a container image, or a source build can use different compile-time defaults. Check the active binary before editing a rotation rule:

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
nginx -V

In the output, look for --conf-path=, --error-log-path=, and --http-log-path=. These arguments reveal the build’s configuration, error-log, and HTTP access-log defaults. Also inspect the files included by the active configuration; Ubuntu commonly includes files from /etc/nginx/conf.d/ and /etc/nginx/sites-enabled/.

Use the paths shown by the running installation when writing a logrotate rule. Rotating a file that Nginx never opens will not solve a logging problem.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.

Understand what Nginx logs

Error logging and severity

error_log records diagnostic events. Its syntax is a destination followed by an optional minimum severity:

error_log /var/log/nginx/error.log warn;

Severity levels are cumulative: warn includes warnings and more severe messages. The directive can write to a file, standard error (stderr), or a syslog: destination. A lower-level configuration block can override an inherited setting.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Access logging and formats

access_log records requests and selects the format used for each line. The module’s default is logs/access.log combined; Ubuntu’s package layout resolves that relative default to the familiar /var/log/nginx/access.log. Explicit paths are clearer in a production configuration.

When several error_log or access_log directives are defined at the same level, Nginx can send events to each configured destination. A directive in a server or location block can therefore add a targeted log or replace an inherited one, depending on how the configuration is written. Check the complete effective configuration when a request appears in an unexpected file.

Configure a standard file-based setup

1. Back up and inspect the active configuration

sudo cp -a /etc/nginx/nginx.conf /etc/nginx/nginx.conf.$(date +%Y%m%d-%H%M%S)
sudo nginx -T | less

nginx -T tests and prints the configuration, including included files. If the installation uses a different --conf-path, substitute that path in the backup and inspection commands.

2. Define a format in the http context

Place custom log_format definitions inside the top-level http { ... } block. A format is declared once and referenced by name from an access_log directive:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
http {
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent"';

    access_log /var/log/nginx/access.log main;
    error_log  /var/log/nginx/error.log warn;

    # server blocks follow here
}

The main format above is equivalent to the familiar combined-style fields: client address, authenticated user, timestamp, request line, response status, response size, referrer, and user agent. Keep the format stable if downstream tools parse it; changing field order can break dashboards and alerts.

Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.

3. Apply a server- or location-specific policy only when needed

To separate one virtual host, define its access log in that server block:

server {
    listen 80;
    server_name example.com;

    access_log /var/log/nginx/example.access.log main;
    error_log  /var/log/nginx/example.error.log warn;
}

A setting at this lower level overrides the inherited setting for that scope. Use location-level logging sparingly: many separate files make retention, permissions, and troubleshooting harder.

4. Consider buffering, descriptor caching, and conditional logging

The access-log module supports buffered writes and open-file descriptor caching. These options can reduce filesystem overhead on high-volume services, but they alter when bytes become visible and how files are reopened. Do not enable them without understanding the resulting flush and descriptor behavior.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Conditional logging can suppress selected requests. A map in the http context can set a variable such as $loggable to zero, and the access log can reference it:

http {
    map $request_uri $loggable {
        default 1;
        /healthz 0;
    }

    log_format main '$remote_addr [$time_local] "$request" $status';
    access_log /var/log/nginx/access.log main if=$loggable;
}

Exclude only traffic that you have deliberately classified as noise. Health checks may be useful during an outage, and conditional rules can hide evidence if they are too broad.

Validate and reload without interrupting traffic

  1. Edit the active file or an included site file.
  2. Run a syntax check before touching the running workers:
    sudo nginx -t
  3. Proceed only when the command reports that the configuration test is successful. Fix missing semicolons, unknown variables, duplicate format names, and permission errors first.
  4. Reload through Ubuntu’s service manager:
    sudo systemctl reload nginx
  5. Generate a request, then inspect the configured destination:
    sudo tail -f /var/log/nginx/access.log
    sudo tail -f /var/log/nginx/error.log

If logs are configured for syslog: rather than local files, inspect the receiving system instead of expecting new lines in /var/log/nginx/. A successful reload proves syntax, not that the destination is reachable or writable.

How Ubuntu logrotate handles Nginx files

logrotate reads its main configuration, per-application rules, and a state file. A rule determines when a file is rotated, how many old copies remain, whether they are compressed, how a replacement file is created, and what action tells Nginx to use the new inode.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord | 6.35mm Jack, Durable Design, Stage and Home Studio Use, Low Noise Shielded Electric Cord for Bass, Keyboard, Amp, Mixer
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by

Before replacing anything, inspect the installed rule:

sudo sed -n '1,200p' /etc/logrotate.d/nginx

The exact shipped file is release-specific. Preserve local changes and match the package’s owner, group, PID path, and reopen action rather than copying an example unchanged.

Option A: move and recreate, then ask Nginx to reopen

This is the usual descriptor-aware approach. Logrotate renames the current file, creates a new file with the requested mode and ownership, and a postrotate action signals the master process. Nginx then closes and reopens its logs, so subsequent entries go to the new file.

/var/log/nginx/*.log {
    daily
    rotate 14
    missingok
    notifempty
    compress
    delaycompress
    create 0640 www-data adm
    postrotate
        [ -s /run/nginx.pid ] && kill -USR1 $(cat /run/nginx.pid)
    endscript
}

daily is the schedule in this example; rotate 14 keeps fourteen rotated files. compress compresses old files, while delaycompress leaves the newest rotated copy uncompressed until the next cycle. missingok avoids an error when a file is absent, and notifempty skips empty files. create 0640 www-data adm is an example only: use the ownership and group expected by the installed package and your local access policy.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The PID path can differ. Confirm it in the active Nginx configuration or service definition before using /run/nginx.pid. The signal command must target the running master process; otherwise Nginx will continue writing to the renamed inode.

Option B: copy and truncate in place

With copytruncate, logrotate copies the current file to its rotated name and truncates the original file in place. Nginx keeps the same open descriptor, so no reopen signal is required:

/var/log/nginx/*.log {
    daily
    rotate 14
    missingok
    notifempty
    compress
    copytruncate
}

The trade-off is a small window during copy and truncation in which writes can be lost or duplicated. Move-and-recreate avoids that particular copy window but depends on a correct reopen action. Do not combine copytruncate with a move-and-recreate create/postrotate strategy casually; choose one descriptor-handling model for each rule.

Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.

Compare the rotation choices

Criterion Move and recreate plus reopen copytruncate
Open descriptor Nginx must close and reopen the file after rotation. The original inode remains open and is truncated.
Write-gap risk Does not use a copy/truncate window; an incorrect or failed reopen can leave Nginx writing to the renamed file. Can lose a small interval of writes while copying and truncating.
Operational dependency Requires the correct PID path and a working postrotate signal or service action. No reopen action is required.
Typical use Preferred when the installed service reliably supports a reopen signal. Useful when descriptor reopening cannot be made reliable and a small write gap is acceptable.

Test rotation safely

First perform a dry run. It reads the configuration and reports what would happen without changing files:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
sudo logrotate -d /etc/logrotate.conf

Review the output for the intended Nginx paths, schedule, ownership, compression, and post-rotation command. To force a real cycle when appropriate:

sudo logrotate -f /etc/logrotate.conf

Afterward, check all of the following:

  • The newly created file has the expected owner, group, and mode.
  • The rotated name exists and older files are retained only up to the configured count.
  • Compression and delayed compression match the rule.
  • A new request produces a line in the current log, not only in the rotated file.
  • The error log contains no permission, reopen, or signal failure.

Remember that logrotate uses its state file to track the last rotation. A forced run is a test operation, not a replacement for choosing a sensible schedule.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Forward logs to syslog instead of, or in addition to, local files

Nginx accepts a syslog: destination for both directives. Parameters include server= (an IP address, hostname, or UNIX socket), an optional port, facility=, tag=, severity=, and nohostname. If no port is supplied, UDP port 514 is used.

error_log  syslog:server=192.0.2.10:514,facility=local7,tag=nginx warn;
access_log syslog:server=192.0.2.10:514,facility=local7,tag=nginx,severity=info combined;

The receiver, transport, firewall rules, and retention policy are separate systems to operate. Forwarding does not automatically preserve a local copy, and an unavailable receiver may make events unavailable to local troubleshooting depending on the configuration.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Approach Strengths Risks and work
Local files with logrotate Simple inspection on the host; explicit compression and retention; continues to work when the network is unavailable. Each host needs disk monitoring, permissions, rotation policy, and collection if centralized analysis is required.
Syslog forwarding Centralizes search, access control, alerting, and retention across hosts. Requires a reachable receiver, network and firewall configuration, transport decisions, and an independent retention policy; local evidence may not exist.
Both Provides local incident evidence and centralized analysis. Consumes more storage and creates two retention and failure paths to maintain.

Troubleshoot common failures

Nginx stopped writing after rotation

  • Check whether the rule moved the file without successfully signaling the master process.
  • Confirm the PID path and that the process receiving USR1 is the Nginx master.
  • Inspect file descriptors for the master and workers with the host’s normal process tools; a descriptor still attached to a rotated filename indicates a reopen problem.
  • Verify that the newly created file is writable by the worker account and has the expected group.
  • Run sudo nginx -t, then reload Nginx if the configuration itself was changed.

The file exists but remains empty

Check that the access_log directive is in the scope receiving the request and that a conditional expression such as if=$loggable is not suppressing it. Confirm that the request reaches this Nginx instance and virtual host, rather than another proxy or container.

Permission denied or logs disappear after reboot

Inspect the directory and file owner, group, and mode created by logrotate. The example 0640 www-data adm is not universal. Match the account that needs to write or read the logs, and ensure the parent directory exists at boot.

Unexpected duplicate or missing entries

Search the complete configuration printed by nginx -T for every access_log and error_log. Multiple destinations at one level can intentionally duplicate output, while a lower-level directive can override an inherited destination. A copytruncate cycle can also account for a small number of missing or duplicated lines during its copy window.

Rotation works but disk usage still grows

Check the number of retained files, whether compression is delayed, and whether other per-server log paths are outside the glob being rotated. Include each deliberately configured path in an appropriate rule, without rotating unrelated application data under the same pattern.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A practical operating checklist

  • Use nginx -V and nginx -T to discover the active build and complete configuration.
  • Define custom log_format in http, then reference it explicitly from access_log.
  • Set error_log severity deliberately; warn records warnings and more severe events.
  • Run sudo nginx -t before every reload.
  • Reload through systemctl, then verify a fresh request in the destination.
  • Inspect the installed /etc/logrotate.d/nginx rule before replacing it.
  • Choose either move/recreate plus a reliable reopen action or copytruncate; document the trade-off.
  • Dry-run with logrotate -d, force a test only when appropriate, and verify ownership, compression, retention, and continued writes.
  • If using syslog, test the receiver and network path separately and decide whether local retention is still required.

Frequently Asked Questions

Where are Nginx logs stored on Ubuntu?

Ubuntu package builds normally use /var/log/nginx/access.log for requests and /var/log/nginx/error.log for diagnostics. Verify the active installation with nginx -V and inspect nginx -T if paths have been customized.

Should I use copytruncate or send Nginx a reopen signal?

Use move-and-recreate with a correct postrotate reopen action when the installed service supports it reliably. Use copytruncate when reopening cannot be made dependable and the possible small write gap is acceptable.

How can I confirm that logrotate will rotate Nginx logs?

Run sudo logrotate -d /etc/logrotate.conf and inspect the reported paths and actions. To perform a real test, use sudo logrotate -f /etc/logrotate.conf, then generate a request and verify that the current log receives it.

Why does a custom access format have no effect?

The log_format declaration must be in the http context, and the exact format name must be referenced by the applicable access_log. A lower-level access-log directive can override the one you edited.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Linux administrationlogrotateNGINXserver loggingUbuntu

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.