October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
VGSources
Blog

Nginx Access and Error Logs: Global HTTP Config vs. Server Blocks

Configure shared Nginx logging in the http block, then override it in individual server blocks only when a virtual host needs separate files, retention, ownership or routing. This guide explains directive contexts, examples, validation commands, internal redirects, conditional logging and syslog destinations.
Length11 min Posted Quest giverVGSources Team

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.

Put shared logging policy in the http block and add a server-level directive only when a virtual host needs a different file, format, retention boundary, ownership model or logging rule. The access_log and error_log directives are independent, and they do not have identical context rules. A server block can inherit a broad access-log policy, override it for one hostname, or disable request logging for a narrowly defined scope.

The most common source of confusion is calling every broad setting “global.” For HTTP request logs, the practical shared scope is usually http. The true Nginx main context is broader, and access_log is not valid there. Error logging can be configured in the main context as well as in http, server and location. Use the narrowest supported scope that matches the operational boundary you actually need.

As an Amazon Associate I earn from qualifying purchases.

How Nginx logging scope works

Nginx configuration is hierarchical. Directives outside a block are in the main context; events and http are nested inside that context; server is nested inside http; and location is nested inside server. A setting at a broad level supplies policy to the configurations below it, while a more specific block can replace that policy when the directive permits it.

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

That hierarchy gives you a straightforward design rule:

  • Use http for one request-log policy shared by several virtual hosts.
  • Use server when one hostname needs its own destination, format, retention boundary, tenant separation or ownership.
  • Use location for a deliberate exception affecting only one URI-handling context.
  • Keep exceptions as close as possible to the virtual host or location that requires them, so the effective configuration is easy to audit.

“Global” therefore does not automatically mean “put it at the top of the file.” It means selecting the broadest valid context that represents the policy. For access logs that is commonly http; for error logs it may be the main context or http, depending on whether you want coverage beyond HTTP.

access_log and error_log are different directives

Access logging records HTTP requests and their outcomes. Error logging records diagnostic messages generated by Nginx and, depending on the configured level, upstream or request-processing problems. They have different modules, valid contexts and inheritance decisions, so placing one does not configure the other.

Directive Purpose Valid contexts Documented default Important behavior
access_log Writes request records using a named log format. http, server, location, if in location, limit_except logs/access.log combined Supports off, multiple destinations and conditional logging with if=.
error_log Writes Nginx diagnostic and error messages. main, http, mail, stream, server, location The primary error log is normally prefix/logs/error.log. Several logs can be specified at the same configuration level; the selected level controls which messages are emitted.

The source-build defaults identify the primary HTTP request log as prefix/logs/access.log and the primary error log as prefix/logs/error.log. Package maintainers often change the prefix or paths, so inspect the loaded configuration on the host rather than assuming those relative paths describe your installation.

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

When an http-level policy is the right choice

Put a common access_log in http when all or most virtual hosts should use the same schema and destination. This is useful for a central collector, one rotation policy, consistent dashboards and simpler configuration review. A server block below that setting can use the shared policy without repeating the directive.

One access log for every virtual host

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;

    server {
        listen 80;
        server_name example.com;
        # Uses the http-level access_log.
    }

    server {
        listen 80;
        server_name api.example.net;
        # Also uses the shared policy.
    }
}

This arrangement gives operations one file to collect and rotate. It also means a line in that file must be interpreted with the hostname, request host, or another field if several sites share the listener. Include a host-identifying variable in your format when the same destination serves multiple names and operators need to filter by virtual host.

Shared error policy at a broad scope

A broad error_log can provide a common baseline, such as a warning threshold, while individual servers add a more specific destination when required. Because error logging supports several destinations at one level, do not assume that naming one file in a nested block makes every other configured destination disappear. Verify the effective configuration and test the resulting files.

When a server-block override is better

Use a separate server-level destination when the virtual host is an ownership or security boundary. Typical reasons include separate customer access, different retention periods, independent incident response, chargeback, regulatory handling, or a requirement that one tenant cannot read another tenant’s request records.

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

Separate access and error files per hostname

http {
    log_format main '$remote_addr - $remote_user [$time_local] '
                    '"$request" $status $body_bytes_sent '
                    '"$http_referer" "$http_user_agent"';

    server {
        listen 443 ssl;
        server_name example.com;

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

The named format is still defined in http, where it can be reused. Only the destination and error threshold are specialized for this server. This hybrid pattern avoids duplicating a long format definition while preserving per-site file ownership.

What a server override changes

An override can change the path, the format, the error severity threshold, or the destination type. It can also turn access logging off for that server. Decide whether the exception should apply to every location in the virtual host; if not, place it in the particular location instead.

Global versus server-block designs

Decision axis Shared http policy Per-server policy
Isolation All selected virtual hosts write to a common destination and schema. Each virtual host can have an independent file or collector destination.
Operational overhead One format, rotation rule and destination to maintain. More paths, permissions, rotation entries and alerts to maintain.
Retention and ownership Common retention unless a downstream system separates records. Different retention, access controls and owners are straightforward.
Troubleshooting Correlating several sites requires filtering the shared stream. A hostname’s records are immediately visible in its own files.
Central collection Simple to forward one stream to a collector. Still possible, but every destination and failure path must be monitored.
Configuration drift Low when sites accept the common policy. Higher if many server blocks carry hand-maintained variations.

There is no documented performance or storage statistic that makes one design universally superior. Choose according to isolation and operations, not an assumed speed advantage.

Give each virtual host its own Nginx logs

To create independent logs, define the format once and add paths inside each relevant server block. Use absolute paths so the destination is unambiguous, create the parent directory first, and make sure the worker account can write the files.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Define or select a log_format in the http block.
  2. Create a directory such as /var/log/nginx/sites with ownership and permissions appropriate for the Nginx worker and your log-collection process.
  3. Add an access_log path and, if needed, an error_log path inside each server block.
  4. Check the complete configuration with nginx -T and syntax/file access with nginx -t.
  5. Reload only after both checks succeed.
  6. Send a request with a distinctive path or header, then confirm which file receives it.

Do not use a variable in a log filename merely to avoid writing server blocks. Variable-based paths can create many files and complicate permissions, rotation and file-descriptor usage. Explicit server-level paths are usually easier to govern when the number of virtual hosts is known.

Disable or reduce logging deliberately

Disable access logging for one server

server {
    server_name health.example.com;
    access_log off;
}

The special off form removes request logging for that scope. It is appropriate for a high-volume health endpoint only when you have another way to observe availability and are comfortable losing request-level evidence. Do not disable logs casually on an authentication, payment, administration or incident-sensitive hostname.

Conditional access logging

The if= parameter lets a request be omitted when the condition evaluates to 0 or an empty string. A common pattern is to keep errors and unusual responses while omitting successful responses:

http {
    map $status $loggable {
        ~^[23] 0;
        default 1;
    }

    access_log /var/log/nginx/access.log combined if=$loggable;
}

Conditional logging changes what evidence exists later. Document the rule, test it with representative status codes, and ensure that a separate security or audit stream is not being unintentionally filtered.

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

Why a request can appear in an unexpected access log

Nginx records a request in the context of the location where processing ends. That location can differ from the original match when an internal redirect occurs. A rewrite, an error-page handoff, an index lookup or another internal transition can therefore move the request into a location with different access-log settings.

Debugging an internal redirect

  1. Run nginx -T and save the complete output so every included file and nested block can be searched.
  2. Find the initial server_name and location match for the request.
  3. Look for rewrite, try_files, error_page, index processing and other directives that can trigger internal processing changes.
  4. Inspect the final location’s access_log and any access_log off setting.
  5. Repeat the request with a unique path and compare timestamps in all candidate files.

This behavior explains why changing the apparent server block may not change the file you are watching: the request may finish in a nested location with its own logging rule.

Validate changes safely

Use the following sequence for every logging change:

  1. Inspect: nginx -T tests the configuration and dumps the loaded configuration files. It is the fastest way to discover an included file or a later override you did not edit.
  2. Test: nginx -t checks syntax and attempts to open files referenced by the configuration. A failure commonly indicates a nonexistent directory, a misspelled path or insufficient permission.
  3. Check filesystem access: confirm that parent directories exist and that the Nginx worker user can create or append to the selected files. Also check that your rotation or collector account can read them.
  4. Reload: nginx -s reload starts workers with the new configuration and gracefully shuts down old workers.
  5. Verify behavior: generate a controlled request, inspect the expected access file, and create a known error if you are testing error-log routing.

A successful syntax test does not prove that your log shipper, rotation schedule or permissions policy is correct. Treat those as separate operational checks.

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.

Error-log levels, missing files and subrequests

Choose an error threshold

The severity level on error_log determines which messages are recorded. A broad warning-level policy is often a practical baseline; a temporary debug setting can be useful during diagnosis but may produce substantial volume. Apply a more verbose level to one server or location when investigating a contained problem instead of increasing verbosity for every tenant.

log_not_found

log_not_found controls whether errors about files that were not found are written to the error log. It is available in http, server and location contexts. Disabling it can reduce noise from scanners requesting random paths, but it also removes a useful signal when a deployment references a missing asset. Scope the change narrowly and understand the diagnostic trade-off.

log_subrequest

log_subrequest controls whether subrequests are written to the access log and is also valid in http, server and location. Enabling it can explain unexpected extra lines generated by authentication checks, includes or internal processing; leaving it disabled can keep the primary request stream easier to analyze.

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

Forward logs to a central collector

Nginx supports syslog destinations for both directives. A destination can be a network address or a UNIX-domain socket, allowing several hosts to send records to one managed collector or analysis system.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
error_log syslog:server=192.168.1.1 debug;
access_log syslog:server=unix:/var/log/nginx.sock,nohostname;

Use a central destination when the operational priority is fleet-wide search, consistent retention, alerting or correlation across hosts. Decide whether the collector needs the hostname embedded in each record; the nohostname option in the UNIX-socket example suppresses the hostname added by the syslog logger, which is useful only when the receiving pipeline supplies that identity elsewhere.

  • Confirm network reachability or socket ownership before switching production traffic.
  • Define behavior for collector outages, including local buffering or an alternate destination where required.
  • Keep sensitive fields out of the format unless the receiving system is approved to store them.
  • Monitor delivery and disk usage; centralization does not remove the need for capacity planning.

Common failure modes and fixes

“My server block still uses the shared file.”

Check that the request is reaching the intended server_name, that the override is inside that exact block, and that no included file defines a later or nested rule. Then check for an internal redirect ending in a location with different logging settings.

“Nginx will not reload after I changed the path.”

Run nginx -t. If it reports an opening error, create the parent directory, correct the path, and grant the worker account the required write permission. Do not reload repeatedly while the configuration test is failing.

“The error file is empty, but requests are working.”

An empty error file can be normal when no messages meet the configured severity threshold. It can also indicate that the request is handled by another server, that a different destination is configured at a broader level, or that the process cannot write the file. Inspect nginx -T, check permissions and deliberately trigger a harmless diagnostic condition in a test environment.

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

“I see duplicate error messages.”

Several error logs can be specified at one level. Review every applicable destination and the effective nested configuration before concluding that Nginx is writing the same event twice by mistake.

“The shared access log has no hostname.”

Add a host variable to the shared log_format, or use per-server files. Without a host-identifying field, records from several virtual hosts can be difficult to separate when they share an address and port.

A practical decision checklist

  • Do all virtual hosts share ownership, retention and schema requirements? If yes, start with one http-level access policy.
  • Does one site require separate access controls, billing, retention or incident handling? Add a server-level destination for that site.
  • Does only one URI need an exception? Put the rule in its final location, and account for internal redirects.
  • Do you need diagnostics outside HTTP as well? Consider the broader contexts available to error_log.
  • Are you filtering successful requests or disabling logs? Record the reason, owner and monitoring replacement.
  • Have you run both nginx -T and nginx -t before reloading?
  • Can the worker write the path, can rotation read it, and can the collector receive it?

The durable pattern is a broad, documented default with the fewest necessary overrides. Keep the format definition reusable, make every exception explicit, and verify the final processing location whenever a request appears in an unexpected destination.

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.

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

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.

More quests from Patch Notes

  1. How to Set Up a RedM (RDR2) Server in 2026: License Key, txAdmin and server.cfg, Step by StepBlog11min
  2. Best RedM (RDR2) Server Hosting in 2026: Comparing Four Hosts on Slots, Memory and PriceBlog10min
  3. How to Host a Mindustry Server in 2026: server-release.jar, Port 6567 and the Commands That MatterBlog7min
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

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.