HomeToolsFormattingNginx Config Formatter

Nginx Config Formatter

Beautify and clean Nginx server block configuration file alignments.

Formatting
Raw Code
Formatted Code

Configuration readability is an operational safeguard

An Nginx configuration can be syntactically valid yet difficult to audit. Nested http, server, location, upstream, map, and conditional blocks determine request behavior, while directive order and inheritance can produce surprises. Consistent indentation helps an operator identify scope before changing a proxy header, cache rule, redirect, or TLS setting.

The Nginx Config Formatter is a line-based indentation aid. It trims each non-empty line, omits blank lines, reduces indentation when a line starts with }, and increases indentation after a line ending in {. You can select two or four spaces and copy the generated text. It does not parse Nginx grammar, insert line breaks into compressed configuration, expand includes, or run nginx -t. Treat it as a reading aid for already line-broken blocks, never as configuration validation.

From rough margins to visible scope

Consider a server block whose directives are on separate lines but poorly aligned:

server {
listen 443 ssl;
server_name example.test;
location /api/ {
proxy_pass http://backend;
proxy_set_header Host $host;
}
}

With four spaces, output becomes:

server {
    listen 443 ssl;
    server_name example.test;
    location /api/ {
        proxy_pass http://backend;
        proxy_set_header Host $host;
    }
}

This makes ownership clearer, but no directive has been checked. The formatter cannot tell whether certificates are configured, the backend upstream exists, headers are appropriate, or the location and proxy_pass URI forms produce the intended upstream path.

A compressed line such as server { listen 80; location / { return 200; } } remains compressed. The tool reacts to line starts and endings; it does not split semicolon-terminated directives or braces inside a line.

Use it as part of change preparation

Keep an untouched copy of the active configuration and work on a small include or server block. Put braces on their own structural lines before pasting. Choose the indentation width already used under /etc/nginx, in your container image, or in infrastructure source control. Compare the output carefully, restoring intentional blank lines if they organize major sections.

Copy the result into the managed source file, not directly into a running container whose contents will be replaced at the next deployment. Review the diff for changed arguments, quoting, variables, regular expressions, comments, and line continuations. The formatter is intended to alter leading layout, but trimming affects every retained line.

Next, test the assembled configuration with the actual Nginx binary and environment. nginx -t checks syntax and referenced resources; nginx -T can print the expanded configuration, which is valuable when includes and inheritance obscure the effective setup. Containerized deployments should run these commands in the same image and with the same mounted files, user, modules, and paths as production.

Reload only after a successful test, using the service manager, container orchestrator, or Nginx signal workflow established for the system. Check error logs, access logs, health endpoints, upstream connectivity, redirects, TLS negotiation, caching, and representative routes. Retain a rollback path.

Indentation is not directive semantics

Nginx directives are valid only in defined contexts. A directive accepted in http may be rejected in server or location; another may inherit from a parent only when absent in the child. This formatter tracks braces but has no directive-context catalog. Attractive nesting does not prove correct placement.

Location matching has its own precedence involving exact matches, prefix locations, ^~, regular expressions, and named locations. Formatting can expose the candidate blocks, but it does not calculate which one wins for a URI. Test concrete requests and inspect debug logging where necessary.

The interaction between location and proxy_pass deserves special care. A trailing URI component can change how the request path is replaced before forwarding. No whitespace formatter can verify that routing intention. Likewise, rewrite, return, try_files, internal redirects, and error-page handling may create multi-stage request processing.

Variables are evaluated at different phases and may be empty depending on context. Quoting and escaping matter in regular expressions, log formats, maps, header values, and shell-generated templates. This page does not interpolate $variables or environment placeholders, which is good, but line trimming may still be unsafe for generated templates that depend on exact text.

Includes, generated files, and secrets

The visible snippet may be only a fraction of the effective configuration. include patterns can load distribution defaults, MIME types, site fragments, or generated upstream lists. Formatting one block does not expose duplicate directives elsewhere. Use nginx -T and deployment manifests to understand the complete graph.

Avoid committing formatted copies of files generated by control panels, service discovery, ingress controllers, or configuration-management systems. Change the template or generator instead. Manual edits to generated output create drift and disappear on reconciliation.

Configuration can contain private hostnames, internal topology, authentication material, signed URLs, or certificate paths. This component performs its transformation in the page code and does not need a server request, but operational policy may still prohibit pasting secrets into any browser page. Redact values or use approved local tooling. Never place private keys directly in an Nginx snippet for formatting.

Comments are retained as trimmed non-empty lines, but empty spacing between comment sections is removed. If comments document a security exception or an ordering dependency, confirm they remain adjacent to the intended directive.

Production checks that formatting cannot replace

Test HTTP to HTTPS redirects without creating loops behind a load balancer. Verify X-Forwarded-For, X-Forwarded-Proto, Host, and trusted proxy handling. Check timeouts and body-size limits for real workloads. Confirm cache keys do not mix authenticated responses and that Set-Cookie behavior is intentional.

For TLS, use current protocol and cipher policy, verify certificate chains and names, and automate renewal. For static files, test roots, aliases, permissions, index behavior, and traversal defenses. For reverse proxies, verify DNS resolution, health behavior, buffering, WebSocket upgrades, streaming, and upstream failure handling.

Security headers require application context; blindly adding or formatting them is insufficient. Content Security Policy, HSTS, framing controls, MIME sniffing, and cross-origin headers can break clients or remain ineffective when incorrectly scoped. Validate responses externally after reload.

Troubleshooting the formatter and the server

A one-line config did not expand. Add safe line breaks manually or use an Nginx-aware pretty printer. This component does not split at semicolons.

Blank section separators disappeared. Empty lines are discarded. Restore intentional spacing after copying.

A brace is indented incorrectly. Closing braces dedent only when they begin the trimmed line; opening braces increase depth only when they end a line.

Formatted configuration fails nginx -t. Use the reported file and line, inspect the effective include context, and compare with the original. Formatting never certifies directive spelling, arguments, modules, or files.

Testing succeeds but traffic fails. Syntax validation cannot guarantee routing, permissions, DNS, certificates, firewall access, or upstream behavior. Inspect logs and send representative requests through the real network path.

Nginx Config Formatter FAQ

Does the formatter validate Nginx syntax?

No. Run nginx -t with the deployed binary and complete configuration.

Can it format an entire config pasted on one line?

Not effectively. Existing line boundaries drive its indentation. Split directives and braces first with syntax-aware tooling.

Which indentation width should I select?

Follow the repository or operations convention. Two spaces keep nesting compact; four make levels more pronounced. Nginx itself does not require either.

Are comments preserved?

Non-empty comment lines remain, with surrounding whitespace trimmed and indentation reapplied. Empty lines between comments are removed.

Does it follow include directives?

No. It processes only pasted text. Use nginx -T to inspect expanded configuration.

Is it safe to reload after copying the output?

Only after diff review, a successful configuration test in the target environment, and application-specific route and security checks. Use the established graceful reload and rollback procedure.

Can this replace an infrastructure formatter in CI?

No. CI should use a pinned, reproducible tool and validate the assembled deployment configuration. This page is best for focused inspection and cleanup.

Record the operational context

When sharing formatted configuration for review, include the Nginx version, loaded modules, deployment topology, and the file’s include path outside the snippet. The same directive can behave differently across versions or fail when a module is absent. State whether another proxy, CDN, ingress, or service mesh sits in front of Nginx, since that affects addresses, schemes, headers, and redirect tests. This context is more valuable than cosmetic consistency when an operator must predict the effect of a reload.

Learn More

Read our comprehensive guide to master this utility.

Read Guide →