Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk11 min

How to Set Up Subdomains With Different Document Roots in Nginx

Set up app and blog subdomains on one Nginx host with separate document roots. This guide covers DNS, server blocks, permissions, reloads, verification, HTTPS, and troubleshooting.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Give each subdomain its own Nginx server block, set a unique server_name and root, point DNS records at the Nginx host, then test and reload the configuration. Nginx uses the request’s Host header to choose the matching block and appends the URL path to that block’s document root.

The routing model: DNS, server_name, and root

Three separate decisions determine what a visitor receives:

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.
  • DNS directs app.example.com or blog.example.com to the server running Nginx.
  • server_name tells Nginx which virtual server block handles the hostname in the HTTP Host header.
  • root supplies the filesystem base directory for that selected block.

For a request such as https://app.example.com/images/logo.png, a block with root /var/www/app.example.com/public; makes Nginx look for /var/www/app.example.com/public/images/logo.png. A request for the same URI on blog.example.com is mapped below the blog block’s root instead. The URL path is appended to the configured root; it is not replaced by the hostname automatically.

When several blocks listen on the same address and port, Nginx compares the Host header with their server_name values. Exact names, wildcard names, and regular-expression names have different matching precedence. If the request does not match the name you intended, Nginx can use the default server for that listen address, which is why a subdomain often displays the generic welcome page.

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

A maintainable directory and configuration layout

For a small, known set of subdomains, use one clearly named block per hostname. Keeping content and configuration separate makes it obvious which files belong to which site and reduces accidental cross-site changes.

Purpose Example path
Application document root /var/www/app.example.com/public
Blog document root /var/www/blog.example.com/public
Application server block /etc/nginx/conf.d/app.example.com.conf
Blog server block /etc/nginx/conf.d/blog.example.com.conf

Linux installations commonly keep the main Nginx configuration under /etc/nginx. A distribution may include files from /etc/nginx/conf.d, or it may use a sites-enabled/sites-available arrangement instead. The important requirement is that the active http configuration includes the files containing your server blocks.

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

Do not assume that creating a file in a directory makes it active. Confirm the include statements used by your installation before troubleshooting a block that appears to be ignored.

Step 1: Create separate roots and unmistakable test pages

Create each directory and put a different file in each one. Distinct test content prevents you from mistaking a cached page or the wrong virtual server for a successful configuration.

sudo mkdir -p /var/www/app.example.com/public
sudo mkdir -p /var/www/blog.example.com/public

sudo tee /var/www/app.example.com/public/index.html > /dev/null <<'HTML'
<!doctype html>
<html><body><h1>Application subdomain</h1></body></html>
HTML

sudo tee /var/www/blog.example.com/public/index.html > /dev/null <<'HTML'
<!doctype html>
<html><body><h1>Blog subdomain</h1></body></html>
HTML

The Nginx worker account must be able to traverse every parent directory and read the files. The exact account name varies by operating system and package. Inspect the service definition or process list rather than assuming a particular user, then grant only the directory and file access required for serving the sites.

Keep writable application data, upload directories, logs, and secrets outside a public document root whenever possible. A root directory is the place Nginx resolves web requests; it should not automatically become a storage location for private configuration.

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

Step 2: Point every subdomain at the Nginx host

Create the appropriate DNS records for each hostname. An A record maps a name to an IPv4 address; an AAAA record maps it to an IPv6 address. Use the record type that matches how clients reach the server, or both when the host supports both protocols.

Hostname Record target Result
app.example.com Nginx host address Requests can reach the application virtual server
blog.example.com Nginx host address Requests can reach the blog virtual server

DNS changes are subject to resolver caching and the records’ time-to-live values. During propagation, one network may still use an older answer while another already reaches the new server. If DNS is not live yet, you can test routing directly with an HTTP client and an explicit Host header, as shown later.

Step 3: Add one server block per subdomain

For static files, the essential directives are a listen address and port, an exact hostname, a root, and an index file.

server {
    listen 80;
    server_name app.example.com;
    root /var/www/app.example.com/public;
    index index.html;
}

server {
    listen 80;
    server_name blog.example.com;
    root /var/www/blog.example.com/public;
    index index.html;
}

Both blocks can listen on port 80 on the same machine. Nginx distinguishes them by the Host header rather than by assigning a separate port to each site. The exact server_name values should match the hostnames clients actually request.

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

With this configuration:

  • http://app.example.com/ resolves to /var/www/app.example.com/public/index.html.
  • http://app.example.com/images/logo.png resolves to /var/www/app.example.com/public/images/logo.png.
  • http://blog.example.com/ resolves to /var/www/blog.example.com/public/index.html.
  • http://blog.example.com/images/logo.png resolves to /var/www/blog.example.com/public/images/logo.png.

Place each block in a file that the active Nginx configuration includes. If your distribution uses a separate enablement step, create the link or enable the site using that distribution’s documented method. A syntactically correct file that is not included has no effect.

Exact names, wildcards, and the default server

Exact hostname matching

An exact name such as server_name app.example.com; is the clearest choice when you know the complete list of subdomains. It makes a typo or an unexpected hostname less likely to be routed to the wrong content.

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

Wildcard matching

Wildcard names can cover groups of hostnames, but they can also capture a request you meant to handle elsewhere. Before adding one, check which names it matches and how it ranks against exact names. A wildcard is useful for a deliberate multi-tenant pattern; it is less suitable when every subdomain has a different root and should be reviewed individually.

Regular-expression names

Regular-expression server names are even more flexible and therefore easier to make surprising. They should be introduced only when the routing rule is intentional and documented. For deterministic routing among a small set of sites, exact names are usually easier to audit.

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

Default-server fall-through

If no intended name matches, Nginx selects the default server for the relevant address and port. That block may contain the distribution’s generic welcome page or another site. Seeing that page usually indicates a hostname, DNS, include, or matching problem—not that Nginx ignored the configured root inside the intended block.

Step 4: Confirm inclusion, test syntax, and reload safely

  1. Check the active include layout. Verify that the file containing each block is referenced from the active http context.
  2. Run the configuration test. Use the test command supplied by your installation, commonly nginx -t. Fix every reported error before reloading.
  3. Reload Nginx through the service manager. A reload applies valid configuration without requiring a full stop and start. Use the service command appropriate to your operating system.
  4. Repeat the test after edits. Editing a file does not change running workers until a successful reload occurs.

A failed syntax test should be treated as a deployment failure: do not force a reload with an invalid configuration. Preserve the last known-good configuration, correct the reported file and line, test again, and only then reload.

Step 5: Verify each hostname, including before DNS propagation

Use a browser or an HTTP client and look for the distinctive content created in each root. Test a file path as well as the index page so that URI-to-root mapping is exercised.

curl -i http://app.example.com/
curl -i http://app.example.com/images/logo.png
curl -i http://blog.example.com/

If DNS does not yet resolve to the server, send the desired Host header to the server’s address. Replace the address with the Nginx host’s actual IPv4 address:

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.
curl -i -H 'Host: app.example.com' http://203.0.113.10/
curl -i -H 'Host: blog.example.com' http://203.0.113.10/

This test separates DNS problems from Nginx matching problems. If the explicit Host-header request returns the correct page but the normal hostname does not, investigate DNS, resolver caching, or an intermediate proxy. If both return the wrong page, inspect the server names, active includes, and default-server selection.

Why a request returns a 404

A 404 generally means Nginx selected a block but could not find the requested URI below that block’s root. Check the complete filesystem path implied by the two values.

Request Configured root File Nginx expects
/ /var/www/app.example.com/public /var/www/app.example.com/public/index.html when that index is configured
/css/site.css /var/www/app.example.com/public /var/www/app.example.com/public/css/site.css
/posts/first.html /var/www/blog.example.com/public /var/www/blog.example.com/public/posts/first.html
  • Confirm spelling, capitalization, and the file extension.
  • Confirm the file exists below the selected root, not only below another subdomain’s root.
  • Check whether a location-specific rule changes how the URI is handled.
  • Inspect the Nginx error log for the path it attempted to open.

A 404 is different from the default welcome page. The welcome page points to a matching or fallback server block serving its own content; a 404 indicates that the selected handling path did not produce the requested resource.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Permission errors: directories as well as files

Reading a file requires more than readable file bits. The worker account also needs execute (traverse) permission on each directory in the path, including parent directories such as /var, /var/www, and the site-specific folders.

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

When the response is “permission denied,” check:

  • Ownership and mode of the document-root directories.
  • Traverse permission on every parent directory.
  • Read permission on the requested file.
  • Mandatory access-control policies or security profiles enabled by the operating system.
  • Whether a symlink points outside an allowed path.

Grant the minimum access needed by the Nginx worker instead of making an entire tree world-writable. After changing permissions, request the same URL again and inspect the error log if the failure remains.

Separate files or one consolidated configuration?

Design Strengths Trade-offs
One file per subdomain Clear ownership, smaller diffs, easy to disable or audit one site More files to manage as the number of hostnames grows
One file containing several blocks Convenient for a tightly related group and a single deployment change Harder to isolate changes; a syntax mistake can affect the whole group
Wildcard block Compact for intentionally uniform hostnames Can capture names unexpectedly and does not give each site an independent root unless additional routing logic is used

For a few subdomains with genuinely different content, separate exact-name blocks are the easiest arrangement to understand. Consolidate only when the sites share an operational lifecycle and the resulting file remains easy to review.

Static roots versus proxied applications

The examples above serve files directly from disk. That is appropriate for static HTML, images, stylesheets, and generated assets. A dynamic application commonly uses a different architecture: Nginx still selects a server block by hostname, but that block forwards requests to an application process instead of resolving every request under a public directory.

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.
Architecture Role of root Typical use
Static serving Defines the filesystem base for requested files HTML, CSS, JavaScript, images, downloads
Reverse proxy May be used for selected static assets, while application requests are forwarded upstream Framework or service listening on another local port or socket

Do not point a static root at an application’s private source tree merely because the application has a directory with that name. Expose only the intended public directory, and keep application secrets and internal code outside paths that Nginx can serve directly.

Adding HTTPS without losing the hostname separation

HTTP and HTTPS are separate listen contexts. When TLS is enabled, create or adapt HTTPS server blocks for the same exact hostnames and ensure each one presents the certificate and content intended for that name. Keep the HTTP handling deliberate—often it redirects to HTTPS, although the redirect policy depends on your deployment.

Do not test only port 80 after enabling TLS. Verify each hostname over the scheme that users will access, and check that the HTTPS block has the correct server_name and root. A correctly configured HTTP block does not prove that an HTTPS request will select the same block.

Troubleshooting by symptom

Symptom Likely cause What to check
Generic Nginx welcome page Host did not match the intended block, or the intended file is not included Requested hostname, exact server_name, active includes, and default server
Wrong subdomain’s content Wildcard or regular-expression match captured the request, or the root is copied incorrectly All matching names, precedence, and each block’s root
404 for an existing-looking URL The file is not below the selected root, or the URI is misspelled Full root-plus-URI path and Nginx error log
403 or permission denied Worker cannot traverse a directory or read the file Directory permissions, ownership, security policy, and symlinks
Configuration changes have no effect Syntax test or reload was skipped, or a different file is active nginx -t, service reload result, and include layout
Works with an IP but not the hostname DNS or Host-header mismatch DNS records, resolver cache, and the hostname sent by the client

Change one variable at a time: first prove that the file exists and is readable, then prove that the configuration is loaded, then prove that the hostname selects the intended block. This order prevents a DNS issue from being mistaken for a filesystem issue.

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

Deployment checklist

  • Each subdomain has an A, AAAA, or environment-appropriate DNS record pointing to the Nginx host.
  • Each public directory contains a distinctive test file.
  • Every hostname has an exact server_name where deterministic routing is required.
  • Every block has the intended unique root and, for static sites, an appropriate index.
  • The configuration file is included from the active Nginx http context.
  • The Nginx worker can traverse directories and read public files without broad write access.
  • The configuration test passes before the service is reloaded.
  • Normal hostname requests return the expected page for every subdomain.
  • Host-header tests are used when DNS propagation is incomplete.
  • HTTPS blocks, if present, are tested separately from HTTP blocks.

Key principle

Different document roots do not require different servers or ports. They require correct DNS, a matching server_name for each hostname, and a distinct root in each selected server block. Once those three layers are verified in order, the default-page and wrong-directory problems become straightforward to isolate.

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 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
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver 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.