vhost (Nginx Virtual Host)

Short definition

A virtual host is a configuration block that tells nginx how to handle requests for a specific domain, subdomain, or IP address, allowing a single server to serve multiple websites or applications simultaneously.

Extended definition

In nginx, virtual hosts are called server blocks. Each server block defines the rules for a particular domain: which port to listen on, where the site’s files live, how to handle SSL, what to do with specific URL paths, and how to proxy requests to upstream applications. A single nginx instance can have dozens or hundreds of server blocks active at once, each handling a completely different domain with completely different behaviour. This makes vhost configuration one of the most frequently edited parts of nginx in any multi-tenant or multi-application infrastructure.

Deep technical explanation

Server block structure: A basic vhost file defines at minimum a server_name, a listen directive, and either a root for static files or a proxy_pass for application proxying. SSL configuration, cache headers, gzip, and access logging are typically added on top.

sites-available and sites-enabled: Ubuntu’s nginx package uses a convention where vhost files are stored in /etc/nginx/sites-available/ and activated by creating a symlink in /etc/nginx/sites-enabled/. This allows vhosts to exist in configuration without being active, making it easy to enable and disable them without deleting files.

Inheritance from nginx.conf: Settings defined in the http block of nginx.conf apply to all server blocks unless overridden. A vhost can override any inherited value locally, which is how per-domain behaviour is achieved without repeating global settings.

Name-based vs IP-based virtual hosting: Name-based virtual hosting, by far the most common, uses the HTTP Host header to determine which server block handles a request. IP-based virtual hosting assigns a dedicated IP to each site, which is rarely necessary unless SSL SNI is not available.

Default server block: If no server block matches the incoming Host header, nginx falls back to the default server block, marked with default_server on the listen directive. This is where you handle misconfigured clients, unknown domains, or catch-all redirects.

Practical examples

A single nginx instance serving marketing.company.com as a static site, api.company.com as a reverse proxy to a Node.js app on port 3000, and staging.company.com with HTTP basic auth and a separate document root, all defined in separate vhost files in sites-available.

Why it matters

vhost configuration is the primary way nginx behaviour is defined per domain. Misconfigured vhosts cause incorrect routing, broken SSL, leaked internal responses, and cache misbehaviour. In a fleet of hundreds of servers, a systematic approach to vhost management is essential.

Share this post

Share this link via

Or copy link