October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk12 min

How to Configure Multiple Domains and Subdomains with Nginx

Host multiple domains and subdomains on one Nginx server with explicit server blocks, correct DNS, SNI certificates, HTTP-to-HTTPS redirects, and a reliable test and troubleshooting workflow.
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. Put each application in its own server block inside the http context, point every hostname in DNS to that server, and use server_name to let Nginx select the right site. For HTTPS, each block needs a certificate and private key that cover its names; SNI allows the names to share port 443.

This guide shows a maintainable layout for static sites and reverse-proxied applications, explains exact and wildcard names, and gives a safe test, reload, and troubleshooting procedure.

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 treats each server block as a virtual server. A block can have its own listening address and port, hostnames, document root, URL locations, proxy upstream, access rules, and TLS certificate. When a request arrives, Nginx compares the requested hostname with server_name and selects the matching block.

For an HTTP request, the hostname normally comes from the Host header. For HTTPS, Nginx can need the hostname during the TLS handshake so it can present the correct certificate through Server Name Indication (SNI); it then evaluates the HTTP request and its Host header. Consequently, a certificate problem can occur before any location rule runs.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.

Keep names intentional. An exact name such as app.example.com is easiest to audit. An alias is simply another name in the same server_name directive. Wildcards and regular expressions are available, but broader matching can route an unexpected hostname to an application.

Plan the hostnames before editing Nginx

Separate sites by responsibility

Create a separate logical block when a hostname needs a different document root, upstream process, authentication policy, logging policy, or certificate grouping. A marketing site and an API may share a machine, but putting them in separate blocks makes ownership and troubleshooting clear.

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

Group genuine aliases

Names that should always serve identical content can share one block:

server_name example.com www.example.com;

Do not group a subdomain merely because it shares a parent domain. If app.example.com proxies to a different process, give it its own block.

Decide how unmatched names should behave

Every listening port has a default server. If a request does not match any declared name, Nginx sends it to that default. Define a deliberate default response rather than allowing an unrelated site to appear for mistyped or hostile hostnames.

Prerequisites: DNS, ports, and files

DNS records

DNS must direct each hostname to the Nginx machine before Nginx can route it. Create an A record for every hostname that should resolve over IPv4. Add an AAAA record only when IPv6 is correctly routed to the server and Nginx listens on IPv6.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.
  • Point example.com explicitly to the server; a wildcard record does not automatically cover the apex.
  • Point www.example.com deliberately, either with its own address record or an alias appropriate to your DNS provider.
  • Add records such as app.example.com for each application.
  • Use a wildcard DNS record only when every matching subdomain should enter the same Nginx endpoint.

Confirm that public DNS returns the intended IPv4 and IPv6 addresses before diagnosing Nginx. Testing a hostname that still resolves to an old server produces misleading results.

Firewall and listeners

Allow inbound TCP 80 for HTTP and certificate challenges, and TCP 443 for HTTPS. Your Nginx configuration must listen on the same address families that DNS advertises. If you publish an IPv6 address but do not listen or route IPv6 correctly, some clients will fail even though IPv4 works.

Configuration layout

You can place all blocks in one file or use a distribution layout with sites-available and sites-enabled links. The important requirement is that the files are included inside Nginx’s http context and that every name is loaded exactly where you expect. A broken symbolic link or an un-included file means the block does not exist from Nginx’s point of view.

Configure HTTP sites

The following example serves a static site and proxies a subdomain to an application listening on localhost port 3000:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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 content block

The first block listens on IPv4 and IPv6 port 80. Both the apex and www names use /srv/www/example. try_files checks for a requested file or directory and returns a 404 when neither exists.

Reverse-proxy block

The second block sends requests to an application on the same host. Passing the original Host lets the application know which hostname the visitor used. The forwarding headers preserve the client chain and the original scheme, which many frameworks use when constructing redirects or secure-cookie decisions. The upstream process must actually be listening on port 3000 and reachable by Nginx.

Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by

Give each block a distinct purpose

Do not put unrelated applications behind one catch-all block just to reduce file count. A separate block lets you restart or replace an upstream independently, apply different limits, and identify the failing hostname from logs.

Add HTTPS for multiple names

Each HTTPS virtual server needs an SSL listener, a certificate chain, and a private key:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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;
    }
}

ssl_certificate should point to a certificate chain suitable for clients, while ssl_certificate_key points to the corresponding private key. Protect the key from unnecessary users while allowing the Nginx worker or master process to read it as required by your operating-system permissions.

How SNI permits one IP

When a browser connects to port 443, it sends the requested hostname in TLS SNI. Nginx uses that name to choose the certificate and server block. This works only when the selected certificate contains the exact hostname or a matching wildcard. An HTTPS default server still receives unmatched names, so a request for an undeclared hostname must not be allowed to expose an unintended application.

Certificate coverage rules

A wildcard such as *.example.com covers one subdomain level, for example app.example.com. It does not cover the apex example.com and does not cover a deeper name such as api.eu.example.com. If both the apex and first-level subdomains are needed, include the apex and wildcard as separate names in the certificate’s Subject Alternative Names, or use certificates whose individual names cover the required hosts.

Certificate approach Coverage Operational trade-off
One certificate per hostname Only the listed name or names Small blast radius for a key, but more issuance and renewal objects to track
SAN certificate Several explicitly listed names, such as the apex and www Fewer certificates, but adding or removing a name requires reissuance
Wildcard certificate One level below the stated domain; it does not include the apex Convenient for many first-level subdomains, but the key protects every covered name and deeper levels need separate coverage

Choose the smallest practical scope. A certificate covering many unrelated services can make renewal simpler, but compromise of its private key affects every name it covers.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.

Redirect HTTP to HTTPS safely

After every intended hostname has a valid certificate and the site works over HTTPS, redirect port 80:

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. Do not enable it before certificate issuance is complete: an HTTP-01 ACME challenge may need a reachable challenge location. Preserve the ACME client’s generated exception, or configure a dedicated challenge location. With DNS-01 validation, the automation must be able to create the required TXT records. The exact workflow depends on the ACME client and DNS provider.

A common arrangement is one port-80 redirect block containing all names and separate port-443 blocks containing each site’s content or proxy rules. If a hostname is not ready for HTTPS, leave it out of the redirect until its certificate and service are ready.

Choose exact names or wildcards

Matching style Example What it matches Best use Main risk
Exact app.example.com Only that hostname Production applications with distinct ownership or behavior Each new hostname must be added explicitly
Aliases in one block example.com www.example.com Several names serving identical behavior Apex and www variants of one site Accidentally grouping names that should be separate
Wildcard *.example.com One label immediately below example.com Many interchangeable first-level subdomains It does not match the apex or deeper names and can route unintended hosts
Regular expression Nginx regex server_name Names matching a pattern Specialized, controlled naming schemes Harder auditing and precedence behavior; use only when exact names are insufficient

For production systems with different applications, explicit names provide the clearest inventory. If you use a wildcard, ensure the DNS wildcard, certificate coverage, and Nginx matching policy all describe the same scope.

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

Separate blocks versus shared blocks

Decision factor Separate server blocks One shared block
Isolation Independent roots, upstreams, limits, and access rules Every name inherits the same behavior unless additional conditions are added
Certificate grouping Each block can use its own certificate or key Names commonly share a SAN or wildcard certificate
Deployment ownership Teams can change one site with less risk to others One change affects all names in the block
Troubleshooting Logs and configuration map directly to a hostname Host-based branching can obscure which rule answered
Recommended scenario Different products, applications, or security policies True aliases such as apex and www for one site
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Install the configuration in a safe sequence

  1. Inventory names and services. Write down every apex, alias, subdomain, static root, upstream address, and intended certificate coverage. Mark which names should share behavior.
  2. Create DNS records. Add the required A records and only the AAAA records that your IPv6 path supports. Wait for public resolvers to return the new addresses.
  3. Prepare content and upstreams. Create document-root directories with the correct ownership and permissions. Start each application and verify its local listening address with an appropriate local health check.
  4. Write HTTP blocks. Add one block per logical site, with explicit server_name, listeners, roots or proxy rules, and any required headers.
  5. Issue certificates. Request certificates whose names cover every HTTPS hostname. Include the apex separately when using a wildcard. Keep private keys readable by Nginx but inaccessible to unrelated users.
  6. Write HTTPS blocks. Add listen 443 ssl for IPv4 and, when supported, IPv6. Set the certificate and key paths and copy the site-specific content or proxy configuration.
  7. Test the complete loaded configuration. Run nginx -t. This checks syntax and attempts to load referenced files, including certificates and keys. Fix every error before reloading.
  8. Reload, do not restart unnecessarily. Use the operating system’s Nginx service manager to perform a reload. A reload applies the new workers while existing connections finish; the exact command varies by operating system.
  9. Verify by hostname. Test each name over HTTP and HTTPS, inspect the returned certificate and response headers, and confirm that static paths and proxied paths reach the intended service.
  10. Enable renewal monitoring. Certificate automation must renew before expiry and reload Nginx after a successful renewal. Test the renewal process in the manner supported by your ACME client.

Validate routing without guessing

Check DNS first

Resolve every hostname from a public network. Confirm that the answer is the server’s intended address and that IPv6 does not lead somewhere different. If DNS is wrong, changing server_name cannot fix the request.

Check the loaded Nginx configuration

Run:

nginx -t

A successful result means the assembled configuration is syntactically valid and the referenced files can be opened. It does not prove that DNS, the upstream application, or the certificate’s hostname coverage is correct.

Test each name, not just the IP

Use a browser or an HTTP client with the real hostname. Testing an IP address sends a different host identity and commonly selects the default server. For HTTPS, inspect the certificate’s subject names and the response headers for the requested hostname.

Confirm the upstream independently

For a proxy site, verify that the application responds on its configured local address and port. If the application is down, Nginx may correctly select the block but return a gateway error; changing DNS or certificates will not repair that upstream.

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.

Troubleshoot the common failures

The wrong site appears

  • Check for duplicate server_name entries on the same address and port. Nginx cannot give two competing blocks the same exact name reliably; remove the accidental duplicate.
  • Check whether the request reached the intended port. Port 80 and port 443 have separate listener sets and often separate blocks.
  • Inspect the default server. An unmatched name goes there, so an undeclared alias or stale DNS record may be landing on the default.
  • Verify that the configuration file is actually included and that a distribution’s enabled-site link points to the current file.
  • Confirm that the client sends the expected hostname and that a proxy or load balancer has not replaced the Host header.

The certificate is wrong or rejected

  • Make sure the certificate contains the exact hostname or a wildcard that matches exactly one subdomain level.
  • Remember that *.example.com does not cover example.com or api.eu.example.com.
  • Check that the HTTPS block’s certificate path and key path belong together and are readable by Nginx.
  • Check SNI behavior with a client that sends the real hostname. An IP-only test may receive the default certificate.
  • Check IPv6 reachability. A client using an incorrect IPv6 path can see a different certificate or no service while IPv4 is healthy.

HTTP works but HTTPS does not

Inspect the 443 listener, certificate files, key permissions, SNI name coverage, and firewall. Since TLS selection occurs before normal HTTP routing, a failure at this stage is not caused by a filesystem location rule.

HTTPS works but the redirect or ACME challenge fails

Ensure the port-80 block includes the hostname and that the redirect does not intercept the HTTP-01 challenge path required by your certificate tool. If using DNS-01, confirm that automation can publish the required TXT record and that public DNS can see it.

The proxy returns an error

Check that the upstream process is running, the address and port in proxy_pass are correct, local firewall policy permits the connection, and the application accepts the forwarded host and scheme. Review Nginx’s error log and the application’s log separately so you can distinguish a routing error from an upstream failure.

Security and operational practices

  • Keep private keys out of web roots and source repositories. Restrict read permissions to the account or process that needs them.
  • Use explicit names for sensitive applications instead of a broad wildcard that could catch a typo or an unplanned tenant.
  • Define a safe default response for unknown HTTP and HTTPS hostnames.
  • Use separate access and error logs when different applications have different operators or retention requirements.
  • Review both IPv4 and IPv6 listeners whenever you add or remove a hostname.
  • Test configuration changes with nginx -t before every reload and keep a known-good configuration available for rollback.
  • Renew certificates automatically, monitor expiry, and verify that a renewal reloads Nginx successfully.

A practical layout for a growing server

A small deployment might have one static site block and one application block. As the server grows, keep a predictable naming scheme, such as one file per logical site, with matching HTTP and HTTPS blocks or a clearly documented redirect block. Store application roots under separate directories such as /srv/www/example and avoid sharing writable directories between unrelated services.

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

For each new subdomain, follow the same sequence: create DNS, decide whether it is an alias or a separate application, add the appropriate block, obtain a certificate covering the name, run nginx -t, reload, and test the hostname over both protocols. This turns a potentially risky edit into a repeatable change.

What one IP can and cannot do

One IPv4 address can serve many HTTP names because the request’s Host header identifies the virtual server. One IPv4 address can also serve many HTTPS names when clients support SNI and certificates cover those names. The limit is not the number of names in a simple configuration; practical limits come from machine resources, certificate-management overhead, DNS design, application capacity, and the complexity of your routing policy.

SNI does not remove the need for correct DNS or certificates. A name that resolves elsewhere never reaches this Nginx instance, and a certificate that omits the requested name will fail before Nginx can proxy or serve the request.

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.

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.

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 from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair 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.