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

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

NGINX configuration is a hierarchy of directives and contexts. A directive is a setting that ends with a semicolon; a block directive contains other directives inside braces and creates a context. The usual HTTP path is main → http → server → location: global settings live in main, HTTP-wide settings in http, virtual hosts in server, and URI-specific behavior in location. Knowing that hierarchy tells you where a setting is legal, which value wins when settings differ, and why an included file sometimes causes a syntax error.

This guide explains the file structure, context rules, inheritance, request routing, include files, static serving and proxying, and a safe edit-and-reload workflow. It applies to open-source NGINX and NGINX Plus; exact package paths and service commands depend on your operating system and installation method.

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

What an NGINX configuration file contains

The primary file is usually named nginx.conf. It is plain text made from two constructs:

  • Simple directives consist of a directive name, optional arguments, and a terminating semicolon, for example worker_connections 1024;.
  • Block directives end with braces and can contain other directives. A block that accepts nested directives is called a context.

Anything outside a block is in the main context. The official beginner guide describes events, http, server, and location as contexts and defines directives outside every block as belonging to main (NGINX Beginner’s Guide).

#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter | 4Pack Type C Female to A Male Cable Converter for Apple Duo 17 16 15 14 Plus,iWatch Watch 12 11 10,iPad 9 8 Air,Airpods 5 4
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Whitespace and line breaks are not significant, so indentation is for people rather than the parser. A semicolon is significant: omitting one commonly produces an error when you test the file. Comments begin with # and continue to the end of the line.

The context hierarchy

Contexts determine both scope and legality. The main traffic-related contexts are:

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.
Context Purpose Typical children or directives
main Global process and logging settings user, worker_processes, error_log, events, http, mail, stream
events Connection-processing parameters worker_connections and event-module settings
http HTTP-wide defaults and modules include, MIME types, logging, upstreams, and server
server One virtual HTTP server selected by address, port, and host name listen, server_name, root, and location
location Handling for a URI set Static-file settings, proxying, access rules, and try_files
mail Mail protocols Mail-proxy configuration
stream Raw TCP and UDP traffic Stream servers and upstreams

For a normal web site, visualize the tree as main → http → server → location. A server block cannot be placed directly in main, and a location cannot be placed directly in http. NGINX checks these context rules while parsing the file. The administration guide’s configuration overview provides the canonical hierarchy and examples (Managing configuration files).

A minimal HTTP configuration, annotated

The following example shows where common directives belong. The comments identify each context; they are not required for operation.

user nobody;                         # main

 events {                             # main → events
    worker_connections 1024;
}

http {                                 # main → http
    include mime.types;

    server {                            # http → server
        listen 80;
        server_name example.com;
        root /srv/www;

        location / {                    # server → location
            try_files $uri $uri/ =404;
        }
    }
}

user is global, connection capacity is under events, and HTTP behavior is under http. The server defines a virtual host, while the location describes what to do with requests whose URI matches that location.

Rank #2
Sale
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter | USB C Dongle with 90W Max Power Delivery, 3×5Gbps USB A Data Ports, for MacBook, Dell, and More (Charger Not Included)
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

How the active configuration file is found

Package layouts are not universal. NGINX Plus documentation lists /etc/nginx as the usual Linux location and /usr/local/etc/nginx on FreeBSD, while open-source packages and source builds may use different paths. Do not assume that a file named /etc/nginx/nginx.conf is active.

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

Ask the installed binary which configuration path it was built to use:

nginx -V

Inspect the output for the --conf-path= build argument. Run the command with the same binary and permissions used by your service if multiple NGINX installations exist. This avoids editing a template or an old installation that the running daemon never reads.

Splitting configuration with include

The include directive inserts another file, or files matching a mask, exactly where the directive appears. Placement therefore controls the context of every line in the included file. The core-module documentation describes this directive and its legal contexts (NGINX core module documentation).

These patterns are common:

http {
    include conf.d/http;
    include vhosts/*.conf;
}

The first form includes one file; the second loads every matching file. Because both statements are inside http, each included file must contain directives valid in http—usually one or more server blocks, maps, upstream definitions, or HTTP-wide defaults. A file containing events {} would be invalid there.

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.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter | 85W Max PD, 2 USB 3.0 & 1 USBC Data Ports, SD/TF Card Reader, for Laptops/Mac and Other Type C Devices (Charger Not Included)
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Likewise, an include inside a server block may contain location blocks, but not another top-level http block. Treat included files as if their contents had been pasted at the include line. This mental model explains both successful modular layouts and errors such as “directive is not allowed here.”

Inheritance and overriding

In general, a child context inherits settings from its parent. A value set in http can therefore become the default for every server and location below it; a value set in a particular child can replace that inherited value. NGINX documents the exact behavior for each directive, including whether inheritance is automatic, merged, replaced, or disabled by a child declaration. Always check the directive’s Context field and inheritance notes rather than assuming that every setting behaves the same way.

Where a setting is placed Intended reach Typical use
http All HTTP servers and locations unless overridden Common logging format, MIME types, or a default root
server One virtual host and its locations That site’s document root, TLS listener, or host-specific headers
location Only requests selected by that location A special API proxy, cache rule, or alternate static directory

Inheritance is not the same as textual order. A directive may be valid at several levels but have special merge rules, and some directives are valid only in one context. If a setting appears to be ignored, first verify that the directive is legal at that level, then read its documented inheritance behavior.

How NGINX chooses a virtual server

For an HTTP request, NGINX first chooses a server block using the listening address and port, then compares the request’s Host value with server_name. If several blocks listen on the same address and port, the name match determines which virtual server handles the request. The request-processing documentation explains this selection sequence (How nginx processes a request).

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

A simplified pair of virtual hosts might look like this:

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray | Data transfer & Fast charging for MacBook, iPhone 17/16/15, iPad, Samsung Galaxy, Apple Watch
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
http {
    server {
        listen 80;
        server_name example.com www.example.com;
        root /srv/example;
    }

    server {
        listen 80;
        server_name api.example.com;
        root /srv/api;
    }
}

A request for api.example.com is therefore evaluated in the second server, while the other names go to the first when they match its declarations. A request with an unexpected or missing host can fall to the default server for that listening address and port, so define an intentional default rather than relying on file order.

How location matching works

After selecting a virtual server, NGINX evaluates its locations. The documented high-level rule is that the most specific literal prefix is selected first; regular-expression locations are then considered in configuration order, subject to NGINX’s detailed matching rules. Read the request-processing documentation when combining prefixes and regular expressions, because a small modifier or ordering change can alter the result.

For example:

server {
    listen 80;
    server_name example.com;

    location / {
        try_files $uri $uri/ =404;
    }

    location /images/ {
        root /srv/assets;
    }

    location ~ .php$ {
        proxy_pass http://php_backend;
    }
}

The literal /images/ prefix is more specific than /. The regular expression for PHP files is evaluated according to the documented regex rules and its order relative to other regex locations. When debugging, list every matching prefix and regex, then verify which one NGINX actually selects rather than inferring behavior from indentation.

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

Serving static files with root

A location can serve files directly. The root directive is valid in http, server, and location. NGINX appends the request URI to the selected root to construct the filesystem path. For instance, with root /srv/www;, a request for /css/site.css maps to /srv/www/css/site.css. The web-server overview and static-content guide document this behavior (NGINX web server; Serving static content).

A compact static site configuration is:

server {
    listen 80;
    server_name example.com;
    root /srv/www;

    location / {
        try_files $uri $uri/ =404;
    }
}

Putting the common root at server makes it the default for all locations in that virtual host. A location can set a different root when a URI subtree maps to another directory. Check filesystem permissions and the resulting path when NGINX returns a 404 even though a file appears to exist.

Best Value
Sale
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display | 85W Max PD, 1 Powered USB-C 5Gbps & 2 Powered USB-A 3.0 5Gbps Data Ports, for MacBook Pro, MacBook Air, Dell and More (Black)
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Passing requests to another server

Locations can proxy requests instead of serving files. A typical arrangement keeps the virtual-host identity and common headers at the server level, then puts the application handoff in a narrowly matched location:

http {
    upstream app_backend {
        server 127.0.0.1:8080;
    }

    server {
        listen 80;
        server_name example.com;

        location /api/ {
            proxy_pass http://app_backend;
        }
    }
}

The important structural point is that the upstream definition belongs under http, while the proxy_pass action belongs in the location that should reach the application. Keep static and proxied URI spaces separate so a broad static location does not capture API requests accidentally.

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

A safe edit, test, and reload workflow

Configuration changes do not affect workers until NGINX successfully loads them. Use this sequence:

  1. Identify the active file. Run nginx -V and confirm the --conf-path= value, then inspect any files reached through include.
  2. Make a reversible edit. Preserve a copy or use version control. Change one logical setting at a time, and keep the surrounding context visible.
  3. Test syntax. Run nginx -t with the intended configuration. The command reports the file and line when a semicolon is missing, a brace is unbalanced, an include cannot be parsed, or a directive is illegal in its context.
  4. Reload after a successful test. Use your service manager’s reload operation, commonly systemctl reload nginx, or send NGINX a reload signal with nginx -s reload. The official administration guide states that reload applies the new configuration without interrupting current requests (Managing configuration files).
  5. Verify the result. Request the affected host and URI, inspect the error and access logs, and confirm that unrelated virtual hosts still respond correctly.

A restart is an alternative, but it is a more disruptive operational action than a reload. If the syntax test fails, do not reload; correct the reported line or restore the last known-good file first.

Common structural failures and fixes

  • “Directive is not allowed here”: the directive is outside a context where its module permits it, or an included file was inserted at the wrong level. Move the include or directive to a legal parent context.
  • Unexpected end of file: a closing brace is missing. Match every { with a }, especially after editing nested locations.
  • Unknown directive: the installed build may not include the module that provides it, or the directive name may be misspelled. Check the build and the directive’s module documentation.
  • Changes have no effect: you may have edited a file that is not active, failed to reload, or been overridden by a more specific server or location. Confirm --conf-path, run nginx -t, reload, and trace virtual-server and location selection.
  • Wrong virtual host: the request’s address, port, or Host does not match the intended listen and server_name. Test with an explicit host header and inspect which server is the default.
  • Wrong file path or 404: calculate the URI-plus-root path, then check that the file exists and that the NGINX worker can traverse and read its directories.

Designing a maintainable configuration

Keep the main file focused on process-wide settings and the top-level contexts. Put shared HTTP defaults in files included from http, and put each virtual host in a clearly named file. Use comments to record why an unusual location or inheritance override exists, not to restate the directive name.

Before adding a directive, answer four questions:

  1. Which context does its documentation permit?
  2. Should the value apply globally, to one virtual server, or only to one URI pattern?
  3. Will a child inherit it, replace it, or merge with it?
  4. Could an include or a more specific location change which configuration is actually selected?

This approach keeps scope intentional, makes includes predictable, and reduces surprises when a configuration grows from one site to many.

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.