October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober 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

How to Configure Multiple Domains and Subdomains with Nginx

A practical Nginx guide to hosting multiple domains and subdomains on one IP, including DNS, separate server blocks, reverse proxies, HTTPS/SNI, wildcard certificates, validation, and troubleshooting.
Length11 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Yes—one Nginx server can host many domains and subdomains, including multiple HTTPS sites on one IP address. Nginx does this with separate server blocks inside the http context. Each block declares the hostnames it owns with server_name, then defines its own files, proxy upstream, access rules, and TLS certificate. Nginx compares the hostname in each request with those names and selects the matching virtual server.

The reliable order is DNS first, then HTTP server blocks, then certificates and HTTPS blocks, followed by configuration testing and a reload. The examples below show a static site at example.com, a proxied application at app.example.com, IPv4 and IPv6 listeners, exact hostname matching, wildcard limits, SNI, certificate automation, and the failure modes that commonly send traffic to the wrong site.

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.

How Nginx chooses a site

Nginx can place multiple server directives in the http context. A server block is a virtual server: it listens on one or more addresses and ports and can define server_name, a document root, location rules, reverse-proxy settings, logging, authentication, and TLS.

The server_name directive determines which block handles a request. For ordinary HTTP, Nginx receives the request’s Host header and compares it with the names on the listeners. For HTTPS, the hostname is normally supplied earlier through TLS Server Name Indication (SNI), allowing Nginx to select a certificate before the encrypted HTTP request is available. A later Host match still matters after the handshake.

#1 Best Overall
Sale
Gaoye Blue Light Blocking Glasses
  • BLUE LIGHT BLOCKING GLASSES: Our blue light glasses for women boast UV400 protection, blocking harmful blue rays from computer screens. With these bluelight glasses women, you can enjoy gaming, reading, or watching TV with no worries of eye strain.
  • EYE RELIEF: Our blue light glasses are engineered to reduce blurry vision or strain caused by prolonged screen time. These womens blue light glasses aid in better sleep by preventing blue light from disrupting your natural sleep cycle, helping you fall asleep faster and enjoy a more restful night's sleep, making them the perfect christmas present.
  • COMFORTABLE: Crafted from durable material, our trendy blue light glasses for woman or blue light glasses men ensure long-lasting comfort. The high-transmittance lenses accessories, gamer gifts for men, help keep your eyes relaxed. Perfect stocking stuffers, gifts for gamers men, christmas gifts for men, halloween costumes.
  • LIGHTWEIGHT: These clear blue light glasses feature a lightweight frame, meaning they’ll stay comfy for long-term wear. Perfect as blue blockers glasses for women or mens blue light glasses, these non-prescription fake glasses for men can be worn throughout the day. The blue light blocking glasses women feature polycarbonate HD lenses, which are anti-reflective and restore true color.
  • WORRY-FREE PURCHASE: If you experience any issues, our support team is ready to assist you quickly. These are the perfect costume glasses for cosplay dressing up.

Use a separate logical block whenever a hostname needs a different application, root directory, upstream service, access policy, or certificate grouping. Several aliases for the same site can share one block:

server {
    listen 80;
    listen [::]:80;
    server_name example.com www.example.com;

    root /srv/www/example;
    index index.html;

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

Here, both example.com and www.example.com serve files from /srv/www/example. A subdomain that runs a separate application gets its own block:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
server {
    listen 80;
    listen [::]:80;
    server_name app.example.com;

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

Keep names intentional and auditable. Exact names are generally easier to review than broad patterns. Nginx also supports wildcard names and regular expressions, but pattern-based routing can make ownership less obvious when several applications coexist.

DNS must point every hostname to Nginx

Nginx cannot route a name that never reaches the server. Create public DNS records for every hostname that users will request, and verify that they resolve to the machine running Nginx before diagnosing a configuration problem.

Hostname Typical record Purpose and limitation
example.com A record to the server’s IPv4 address The apex must be declared explicitly; a subdomain wildcard does not include it.
www.example.com A record, or an intentional CNAME where your DNS provider permits it Must be listed in the relevant server_name directive.
app.example.com A record to the same host Routes to the application block when that exact name is declared.
Any hostname over IPv6 AAAA record to a correctly routed IPv6 address Only publish this when the host firewall, network route, and Nginx IPv6 listener work.
*.example.com Wildcard DNS record Sends matching names to the same entry point, but should not be used when subdomains need independent DNS destinations.

Point the apex and aliases deliberately. Do not assume that a wildcard record covers example.com. After changing DNS, query each name from a public resolver and confirm that both A and, if present, AAAA answers are intended. A stale resolver cache can make a correct Nginx change appear ineffective, so test from more than one network when a change is urgent.

Rank #2
Windex Gaming Cleaning Wipes, Pre-Moistened Wipes to Instantly Clean all Gaming Gear and Electronics, Resealable Packaging for a Freshness Lock, 25 count (Pack of 1)
  • WINDEX GAMING WIPES: effortlessly clean all your gaming gear and gaming electronics in one easy step with our new Windex Gaming Wipes
  • AMMONIA FREE: our ammonia-free formula is safe to use on all of your favorite gaming equipment like consoles, headsets, controllers, screens, keyboards, and more
  • PRE-MOISTENED WIPES: each wipe instantly removes dust, dirt, and stubborn smudges and fingerprints leaving a streak-free shine
  • ANTI-STATIC: great for cleaning and wiping down your gaming gear and electronics leaving behind no visible residue
  • COMPACT RESEALABLE PACKAGE: store your pack of Windex Gaming Wipes anywhere in your home for whenever a quick and easy wipedown is needed

Choose a configuration layout

The layout on disk is less important than the loading context. Every server block must ultimately be included inside Nginx’s http context. Some distributions provide sites-available and sites-enabled, commonly using symbolic links; others use a single configuration file with an include directory. Follow the layout supplied by your operating system and make sure a file is actually included.

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.
Approach Best fit Advantages Trade-offs
One block per application or site Different roots, upstreams, owners, or security policies Isolation, clear deployment ownership, easier troubleshooting, independent certificate choices More files and repeated listener lines
One block with several aliases Names that are genuinely the same site One root and one set of rules; aliases stay synchronized All aliases share redirects, logs, policy, and certificate coverage
Wildcard name Many one-level subdomains with the same behavior Fewer names to maintain Risk of unintended routing; does not include the apex or deeper names

Give each production block a unique, intentional set of names. Accidentally declaring the same exact name in multiple blocks makes the result dependent on which block Nginx treats as the default for that listener, rather than on the application owner’s intent.

Build the HTTP configuration

Start without redirects so that DNS, hostname matching, and the application response can be tested independently. Create a static-site block and a reverse-proxy block such as these:

server {
    listen 80;
    listen [::]:80;
    server_name example.com www.example.com;

    root /srv/www/example;
    index index.html;

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

server {
    listen 80;
    listen [::]:80;
    server_name app.example.com;

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

Static files

Create the directory named by root, place the intended index file there, and ensure the Nginx worker can read the directory and files. try_files $uri $uri/ =404; serves an existing file or directory and returns a 404 instead of silently passing an unknown path elsewhere.

Reverse-proxy applications

The proxy_pass target must be reachable from the Nginx host. The forwarded Host, client-chain, and original-scheme headers let the upstream application generate correct links, logs, redirects, and security decisions. Configure the application itself to trust forwarded headers only according to its framework’s rules; forwarding a header does not automatically make it trustworthy from every network.

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.
Rank #3
Sale
LISEN Cell Phone Stand Phone Holder for Desk, Office Decor Gadgets for Men
  • Ergonomic & Adjustable Design: Fight "text neck" and improve your posture. Designed for comfort, it offers an adjustable height (7.1in-8.5in) (1.4in adjustable range) and angle (5°-85°) Please note: cell phone stand is only 9 inches tall—the length of a standard pencil
  • Without blocking subtitles Perfect for office desk Tiktok Face Time Zoom video—this is the ultimate kitchen desk essential for phones! Perfect viewing experience while reducing neck back strain, A must-have for gamers streamers desk, and anyone who values both style and support!
  • Sleek & Stable Design fits Otterbox Case: Say goodbye to bent cables, tangles, and tip-overs! LISEN’s stylish adjustable desk phone holder features a built-in charging hole and smart cable management, keeping your phone secure and your workspace clutter-free cool gadgets for men
  • ANTI-SLIP DESIGN free hands: The under 10.00 items easy gadgets back and the bottom of this kitchen essentials for women are fully covered by anti-skid silicone, which LISEN stand up desk decor can provide maximum protection device from any scratches and slides
  • Your Perfect Viewing Companion:If your product arrives damaged or breaks within 365 days, reach out to LISEN for a quick and hassle-free solution. Struggling with assembly, like tightening the screw? We’ve got your back! Your experience matters to us. (Product including: phone Holder stand*1, screw*1, hexagon screwdriver*1, specification*1)

IPv4 and IPv6 listeners

listen 80; accepts IPv4 traffic, while listen [::]:80; accepts IPv6 traffic. Do not publish an AAAA record until IPv6 reaches this host and the firewall allows the port. Otherwise, some users will connect over IPv6 and see a timeout even though IPv4 testing succeeds.

Configure HTTPS for multiple names

Each HTTPS virtual server needs a TLS listener, a certificate, and the matching private key. A certificate must contain the requested hostname as an exact name or as a matching wildcard. SNI allows several HTTPS names to share one address and port, but it cannot make an uncovered name valid.

server {
    listen 443 ssl;
    listen [::]:443 ssl;
    server_name example.com www.example.com;

    ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    root /srv/www/example;
    index index.html;

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

server {
    listen 443 ssl;
    listen [::]:443 ssl;
    server_name app.example.com;

    ssl_certificate     /etc/letsencrypt/live/app.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/app.example.com/privkey.pem;

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

Exact names, SANs, and wildcards

An exact certificate can list several names through Subject Alternative Names (SANs), such as the apex and its www alias. A wildcard such as *.example.com covers one subdomain level, including app.example.com, but not example.com and not api.eu.example.com. If both the apex and arbitrary one-level subdomains are required, include the apex and wildcard as separate certificate names. A deeper hostname needs its own exact name or an appropriate certificate strategy.

Certificate strategy Coverage model Operational benefit Risk or constraint
One certificate per hostname or application Only listed names Small blast radius if a key is exposed; ownership is obvious More issuance and renewal records
One SAN certificate Several explicitly listed names Fewer certificate files and renewals Adding or removing one name changes the shared certificate; all names must be covered together
Wildcard certificate One level below its base domain Convenient for many similar subdomains Does not cover the apex or deeper levels; the wildcard private key protects every covered name

Protect private keys

The certificate chain may be broadly readable, but the private key should be readable by Nginx and protected from unnecessary users. Use the permissions and group arrangement supported by your operating system, keep backups protected, and avoid placing private keys in application directories or source-control repositories.

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

Redirect HTTP only after HTTPS works

After every intended hostname has a valid certificate and responds correctly on port 443, redirect port 80:

Rank #4
Ledagic IC+RGBW USB Powered Led Light Bar with App & Remote Control, 2 Pack
  • Easy Installation: Our gaming lights have been designed to enhance your entertainment experience. Simply position the led light bar next to your TV or game console to create a game room environment with ease. They come with USB power and a 60 inch cord for direct mounting and mobility
  • Audio Syncing & Extensive Mode: The built-in high-sensitivity music sensor allows you to sync the TV led lights to your favorite music. Lights react and move to the beat of music, film and game audio, creating an incredible immersive sound and light experience – and all without the need for an additional hub. You can choose from 64+ patterns, including strobe, illusion, jump, energy, gradient, running, chasing, fluttering mode etc. Each mode can be applied to different scenes
  • 64+ Chasing IC+RGB & W Effect: The independent control design of IC+RGB and white all-in-one multifunctional rgbw led bar lights monitor backlight allows you to easily switch the led lights for desk between IC+RGB and white to enjoy a variety of lighting effects, you can choose white lighting mode with high brightness for better illumination when working, etc. Choose IC+RGB lighting mode when you need to create an entertaining atmosphere for the light show, 16 million colours of Color changing rgb light bar let you dance to the beat and create a dynamic party atmosphere
  • Dynamic and Dimmable Lights: 1%-full brightness free brightness adjustment gives you the flexibility to adjust dimmable led light bar for room decorations or a variety of occasions
  • USB Powered: USB light bars for room can be powered by powernank, usb charger, TV, Monitor, laptop PC mainframe, making behind TV led lighting bar easy to install in any location.TV led lights are powered by the TV usb interface / PC mainframe, can be turned on/off synchronously with TV / PC
server {
    listen 80;
    listen [::]:80;
    server_name example.com www.example.com app.example.com;
    return 301 https://$host$request_uri;
}

The redirect preserves the requested host and path. Test each hostname over HTTPS before enabling it; otherwise a certificate or DNS mistake becomes harder to diagnose because every HTTP request immediately changes protocol.

Certificate challenge paths

If an ACME client uses HTTP-01 validation, keep its challenge location reachable on port 80 or preserve the exception generated by that client. A blanket redirect can coexist with validation only when the client and challenge handler are configured for it. DNS-01 validation instead requires automation to create the required TXT records. The exact workflow depends on the ACME client and DNS provider. Certificate identifiers should correspond to the names declared in the relevant server_name blocks, and renewal automation must be tested before certificates approach expiry.

Use a deliberate default server

An HTTPS listener still needs a response for an unknown name, a missing SNI value, or a request whose hostname does not match your intended blocks. Nginx will use a default server for unmatched traffic. Make that behavior deliberate: return a simple 444/404-style response or a neutral landing page rather than exposing the first application’s content. Do not rely on file order as an access-control mechanism.

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

When a name unexpectedly shows another site, inspect whether it is missing from server_name, duplicated in another block, sent to a different port, or falling through to the default server. The same checks apply when a proxy receives a request with an unexpected Host value.

Validate and deploy safely

  1. Confirm DNS. Resolve every apex, alias, and subdomain and verify the returned A and AAAA addresses are the intended Nginx host.
  2. Review loaded files. Confirm each configuration file is included inside the http context and that distribution-specific symbolic links are present.
  3. Test the complete configuration. Run nginx -t. Fix every syntax error, missing certificate file, duplicate directive problem, and permission failure before reloading.
  4. Reload through the operating system’s service manager. A common command is sudo systemctl reload nginx; use the equivalent command when your system uses a different supervisor.
  5. Test by hostname, not only by IP address. Request each HTTP and HTTPS name. Testing the IP alone can select the default server and hide a hostname-specific error.
  6. Inspect TLS and headers. Check the certificate names, issuer chain, HTTP status, redirect target, and response headers for every name. Confirm the proxied application sees the expected host and scheme.
  7. Check logs after the first real request. Access and error logs reveal which listener and upstream handled traffic, while application logs show whether forwarded headers or path assumptions caused a failure.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshoot by symptom

The wrong website appears

  • Check for duplicate exact names across files.
  • Verify the request reaches port 80 or 443 as intended and that the block listens on that port.
  • Check whether the hostname is absent from server_name and therefore reaches the default server.
  • Confirm the client is sending the expected hostname and that a proxy or load balancer is not replacing the Host header.
  • Run nginx -T where available to inspect the fully assembled configuration, then search the output for every occurrence of the name.

HTTPS fails but HTTP works

  • Inspect SNI coverage: the certificate must contain the exact name or a matching one-level wildcard.
  • Check the ssl_certificate and ssl_certificate_key paths, file existence, and Nginx read permissions.
  • Confirm the 443 block has listen 443 ssl; and, for IPv6 users, listen [::]:443 ssl;.
  • Test IPv4 and IPv6 separately if an AAAA record exists. A broken IPv6 route can fail before the working IPv4 listener is tried.
  • Remember that a certificate mismatch occurs during the TLS handshake, before an HTTP location rule can repair it.

DNS resolves incorrectly

  • Compare public A and AAAA answers with the server’s actual addresses.
  • Remove an obsolete AAAA record if IPv6 is not ready.
  • Check wildcard DNS and explicit records for conflicting intentions; an explicit subdomain record should be used when it must go somewhere other than the wildcard destination.
  • Allow for resolver caching after a record change, but do not use caching as an explanation for a consistently wrong authoritative answer.

The proxy returns redirects to the wrong scheme or hostname

  • Verify proxy_set_header Host $host; and proxy_set_header X-Forwarded-Proto $scheme; are present in the intended block.
  • Configure the upstream framework to trust those headers only from the Nginx network.
  • Check whether the application has its own canonical-host or HTTPS redirect that conflicts with Nginx’s redirect.

Operational patterns that prevent outages

Keep ownership boundaries clear

Use a dedicated block and log policy for an application that has a different owner or deployment cycle. This lets you reload one assembled configuration while keeping the intent of each site visible, and it reduces the chance that a change for one hostname alters another.

Best Value
Sale
HUANUO FlowLift™ Dual Monitor Stand, Fully Adjustable Gaming Monitor Desk Mount for 13–32″ Computer Screens, Full Motion VESA 75x75/100x100 with C-Clamp & Grommet Base, Each Arm Holds 4.4 to 19.8 lbs
  • Compatible with Wide Screens - To ensure compatibility with the dual monitor mount, your each monitor must meet three conditions at the same time: First, computer screens size range: 13 to 32 inches. Second, screen weight range: 4.4 to 19.8 lbs. Third, the back of the monitor screen must have VESA mounting holes with a pitch of 75x75mm or 100x100mm.
  • Regarding the compatibility with desks - Your desk must meet three conditions at the same time: First, desk material: Only wooden desks are recommended, plastic or glass desks cannot be used. Second, desk thickness range: 0.59" - 3.54". Third, the bottom of the desk should not have any cross beams or panels, as this will interfere with installation. We recommend carefully checking that your desk and monitors meets all above conditions before purchasing.
  • Dual C-Clamp Hold - Worried your dual monitors might wobble or slip? Our upgraded base uses a larger platform plus a dual C-clamp structure to lock the dual monitor arm firmly to your desk. Each arm safely keeps your screens steady while you type, click and game—no shaking, no sliding, just a clean and secure setup you can trust every day. It also provides Grommet Mounting installation choice, both options ensure stable and secure fixation for your 0.59" - 3.54" desk.
  • Full-Motion Adjustment For Comfortable View - Pull the screen closer when you’re deep in a spreadsheet, push it back to watch videos, or rotate to portrait for coding — moving everything smoothly with just one hand. The monitor stand offers +85°/-50° tilt, ±90° swivel and 360° rotation. Raise your monitor up to 15.75″ to support a healthy sitting posture. Whether you’re working from home, gaming through the night, or switching between video calls and documents, getting the screens to your natural line of sight helps relieve neck, shoulder and back strain so you can stay focused longer with less fatigue.
  • Keep Your Desk Organized: By lifting both screens off the desktop, this dual monitor stand opens up valuable space for your keyboard, notebook, docking station or a simple, clutter-free work area. Built-in cable management guides wires along the arms, keeping cords out of sight and out of the way. Enjoy a tidy, modern workstation that looks as good as it feels to use.

Plan certificate grouping consciously

Group names in a SAN certificate only when their renewal schedule and security ownership are compatible. A wildcard simplifies coverage for many one-level subdomains, but compromise of its private key affects all of them. Per-host certificates require more renewals but limit that exposure.

Test renewals, not just initial issuance

Renewal automation must be able to read the private key destination, complete its HTTP-01 or DNS-01 challenge, and reload Nginx after replacement. A successful first issuance does not prove that the scheduled renewal path, DNS API credentials, or challenge location will still work.

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

Keep a rollback path

Store the last known-good configuration, certificate references, and DNS changes together. Before a planned change, know how to restore the previous file and reload only after nginx -t passes. If a reload fails, Nginx keeps the running configuration; fix the reported error before attempting another deployment.

Quick decision checklist

  • Does every public hostname have an intentional A record, and an AAAA record only when IPv6 works?
  • Is each hostname declared exactly where its root, upstream, and access policy belong?
  • Are aliases sharing one block only when they truly represent the same site?
  • Does every HTTPS certificate cover every name in its block?
  • Are apex, wildcard, and deeper subdomains treated as different certificate and DNS scopes?
  • Is the unmatched-name default response deliberate?
  • Did nginx -t pass on the fully assembled configuration before reload?
  • Have HTTP, HTTPS, certificate selection, redirects, and proxied headers been tested using each real hostname?

The Bottom Line

Multiple domains and subdomains work reliably on one Nginx host when DNS points each name to the server, each application has an intentional server block, and every HTTPS name is covered by the certificate selected through SNI. Build and test HTTP routing first, add certificates and redirects second, then validate each hostname over both IPv4 and IPv6 before treating the deployment as complete.

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.

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
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.