DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
FREEDOM251

Freedom251 › Blog › DNS

How to Set Up Catch-All Subdomains in Nginx

By Freedom251 Team · · 12 min read

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

To route arbitrary subdomains, configure both layers: create a DNS wildcard such as *.example.com that points to the Nginx host, then add an Nginx wildcard server_name and a default_server for unmatched Host headers. Keep exact-name server blocks for applications that need their own backend. HTTPS adds a separate certificate requirement: a wildcard certificate covers only one label level, and wildcard certificates must be issued with DNS-01 validation.

What a catch-all subdomain setup actually does

A catch-all arrangement answers two different questions:

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.
  • Can the hostname reach your server? DNS decides this. A wildcard record can direct names that have no more-specific record to the Nginx host.
  • Which Nginx server block handles the request? Nginx decides this after receiving the connection and Host header. Exact names, wildcard names and the default server determine the selected block.

These layers are independent. A perfect Nginx configuration cannot receive tenant.example.com if DNS returns no address for it. Conversely, a wildcard DNS record does not choose a website or proxy target; it only gets the request to an IP address.

There are two useful meanings of “catch-all”:

  • Domain wildcard: handle any host below one domain, such as alpha.example.com or customer.example.com.
  • Port default: handle any Host header for which no more-specific server name exists on a particular listen address and port.

A reliable design normally combines both. DNS sends unknown subdomains to the machine, the wildcard block supplies common behavior, and a default_server catches requests that do not match any named site at all.

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

Choose the hostname scope before changing Nginx

One level below a domain

The usual pattern is *.example.com. It is intended for names such as app.example.com, shop.example.com and random.example.com. It does not describe a name two labels deeper, such as east.shop.example.com; that is a separate hostname level for both DNS and TLS purposes.

The apex plus its subdomains

The bare domain, example.com, is not the same DNS name as www.example.com. If the same Nginx behavior should apply to the apex and all first-level subdomains, Nginx supports the special form .example.com, which matches both the apex and wildcard names. In DNS, you generally still need an apex record in addition to the wildcard record because a wildcard does not replace an explicit apex record.

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

Completely unrelated Host headers

If the server receives a request for unknown-other-domain.test, that name is outside example.com. It can still be routed to your chosen Nginx block when that block is the default_server for the relevant listen port. This is a port-level fallback, not a DNS wildcard for every domain on the internet.

Configure DNS first

Create the wildcard record

At your DNS provider, add a wildcard record for the zone. An A record points to an IPv4 address; an AAAA record points to an IPv6 address. Use the address on which Nginx listens.

*.example.com    A       203.0.113.20
*.example.com    AAAA    2001:db8::20

The exact interface and record names vary by provider. Wildcard synthesis follows DNS rules described by RFC 4592: an unanswered name can be synthesized from a wildcard, but a more-specific record takes precedence. For example, an explicit api.example.com record can point somewhere else while other names continue to use *.example.com.

Add an apex record when needed

If users must reach example.com, create an A and/or AAAA record for the apex according to your provider’s supported record type. Some providers use an alias-style record for an apex because a traditional CNAME is not permitted there. The important result is that the apex resolves to the intended service independently of the wildcard.

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

Check DNS from outside your provider’s dashboard

Test a name that has never had an explicit record. Query both address families if you publish both:

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.
dig +short random-test.example.com A
dig +short random-test.example.com AAAA

The response should contain the Nginx host’s address. If it is empty, points to another service, or returns an unexpected address, stop at DNS troubleshooting; Nginx has not received the request yet. Remember that recursive resolvers may cache an earlier answer until its TTL expires.

Understand Nginx name matching and the real catch-all

Wildcard names handle the intended domain

Use a leading wildcard in the server block:

server {
    listen 80;
    server_name *.example.com;
    # locations, root or proxy settings
}

Nginx compares an incoming Host header with configured names. An exact name such as app.example.com takes precedence over a wildcard. When several wildcard names could match, the longest applicable wildcard is selected. This lets you keep broad defaults while carving out more-specific subdomains.

If you want the apex and first-level subdomains in one named match, use:

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

The leading dot is a documented shorthand with a different meaning from a literal hostname beginning with a dot: it matches example.com and names beneath it.

server_name _ is not the catch-all mechanism

The underscore is commonly placed in examples because it is not normally a real hostname. It does not grant special catch-all behavior. Nginx’s own documentation states that the catch-all or default server cannot be specified by server_name; it is a property of listen.

Declare the fallback on the listen directive:

listen 80 default_server;

For a given address and port, Nginx sends a request whose Host header matches no better server name to the server marked default_server. If no block is marked, Nginx uses the first server for that listen socket, which can change when configuration files are reordered. Mark the intended fallback explicitly instead of relying on file order.

Build an HTTP wildcard and default configuration

The following pattern gives unknown hosts a controlled site while preserving a dedicated application:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord | 6.35mm Jack, Durable Design, Stage and Home Studio Use, Low Noise Shielded Electric Cord for Bass, Keyboard, Amp, Mixer
  • [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
# Fallback for unknown hosts and wildcard subdomains
server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name *.example.com;

    root /srv/www/default;

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

# Named application; exact match wins over the wildcard
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-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

Replace the document root and upstream with paths and services that exist on your machine. The first block is both the wildcard handler for first-level names and the default for unmatched hosts on port 80. The second block remains independent: a request for app.example.com reaches the application on port 3000 rather than the static fallback.

If the apex should use the same content, change the first block’s name to .example.com or add example.com explicitly. If you need unrelated domains to land in the same fallback, leave the block as the default server; the default selection covers hosts that do not match its listed name.

Keep default content deliberate

A default server is exposed to malformed, mistyped and automated requests. Serve a minimal landing page, a clear 404 response, or an intentional application entry point. Do not accidentally expose a directory containing configuration files, deployment artifacts or backups. Use restrictive file permissions and a root directory containing only public assets.

Configure HTTPS without a certificate mismatch

Create a TLS default block

HTTPS needs its own listen socket and certificate configuration. A basic fallback looks like this:

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

    ssl_certificate     /etc/nginx/tls/example.com/fullchain.pem;
    ssl_certificate_key /etc/nginx/tls/example.com/privkey.pem;

    root /srv/www/default;
    location / {
        try_files $uri $uri/ =404;
    }
}

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

    ssl_certificate     /etc/nginx/tls/app.example.com/fullchain.pem;
    ssl_certificate_key /etc/nginx/tls/app.example.com/privkey.pem;

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

Use a certificate whose names cover every hostname the fallback is expected to serve. Keep a separate HTTPS block when an application needs a different certificate, backend or policy. The default server also determines what is presented when no more-specific TLS server is selected.

Know the one-label wildcard limit

A certificate for *.example.com covers names such as app.example.com, but not a.b.example.com. The deeper name needs additional coverage, such as another certificate name or a certificate for the appropriate parent wildcard. This is a certificate naming rule, not an Nginx routing limitation. A request can reach Nginx correctly and still show a browser warning if the certificate’s Subject Alternative Names do not include the requested host.

Request wildcard certificates with DNS-01

Let’s Encrypt’s HTTP-01 challenge cannot issue wildcard certificates. DNS-01 can: the certificate authority asks you to publish a TXT value at _acme-challenge.example.com (or the corresponding validation name), then verifies that public DNS record. Use an ACME client that can update your DNS provider through its API when possible, because automated renewal avoids outages caused by an expired wildcard certificate.

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.

For a certificate covering both the apex and first-level subdomains, request both names, for example example.com and *.example.com. The apex is not covered by the wildcard name alone.

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

Deploy the configuration safely

  1. Confirm DNS. Publish the wildcard record and any required apex record. Verify an arbitrary test name resolves to the Nginx address from a public resolver.
  2. Install the HTTP blocks. Place the wildcard/default block and all explicit application blocks in the active Nginx configuration directory. Ensure only one server is marked default_server for each address-and-port pair.
  3. Check syntax before reloading. Run sudo nginx -t. Fix every reported error; a reload should never be attempted after a failed test.
  4. Reload without dropping connections. Run sudo systemctl reload nginx on a systemd-managed host, or use the service manager appropriate to your operating system.
  5. Test an explicit name and an undefined name. Request the dedicated application and a random subdomain. The first must reach its own backend; the second must return the fallback content.
  6. Add TLS only after HTTP routing is correct. Complete DNS-01 validation, install the certificate and key with permissions that allow Nginx to read the key, then add the 443 blocks.
  7. Validate and reload again. Run sudo nginx -t, reload, and test both HTTP and HTTPS. Inspect the certificate presented for each hostname, not just the HTTP status code.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Test routing from the client side

Verify the public DNS answer

dig +short random-test.example.com
dig +short app.example.com

Compare the results with the intended addresses. An explicit DNS record for app.example.com may intentionally differ from the wildcard result.

Test HTTP host selection

curl -i http://random-test.example.com/
curl -i http://app.example.com/

Use response headers or a distinctive body in the fallback site so you can tell which block answered. If DNS is not ready, you can test the Nginx listener directly with a Host header from a machine that can reach the server:

curl -i -H 'Host: random-test.example.com' http://203.0.113.20/

This bypasses normal name resolution and isolates Nginx matching, although it does not prove that public DNS is correct.

Inspect HTTPS and certificate names

curl -Iv https://random-test.example.com/
curl -Iv https://app.example.com/

Check the certificate subject and SAN list in the verbose output or your browser’s certificate viewer. A successful TCP connection with a name warning indicates certificate scope or selection, not necessarily a DNS failure.

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

Troubleshoot by locating the failing layer

The random subdomain does not resolve

Check the wildcard record spelling, zone, record type and target address. Look for a more-specific record that overrides it, and query authoritative and public recursive servers if answers disagree. Until a resolver returns the Nginx address, changing server_name cannot help.

The name resolves but the wrong site appears

First verify the port and address in every listen directive. Then inspect all loaded server blocks and look for an exact server_name or a longer, more-specific wildcard. Those names take precedence over the broad wildcard. Confirm that the intended fallback is marked default_server on the same listen socket; a default on port 80 does not become the default on port 443.

server_name _ seems ineffective

Replace the assumption that the underscore catches everything. Put default_server on the relevant listen directive and ensure no competing default exists for that address and port. Keep a meaningful wildcard or explicit name list for requests you want to match by hostname.

HTTPS reports a name mismatch

Compare the requested name with the certificate SANs and wildcard depth. *.example.com does not cover a.b.example.com or the bare example.com. Install a certificate containing every required name, or route deeper names to a certificate designed for their scope.

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.

Wildcard certificate issuance fails

Use DNS-01, not HTTP-01. Confirm that the ACME client created the TXT record at the required _acme-challenge name and that the record is publicly visible. Common causes include updating the wrong DNS zone, leaving stale TXT values, or attempting validation before DNS propagation completes. Once issuance succeeds, make sure the renewal process can repeat the DNS update automatically.

Only some networks reach the service

Compare A and AAAA answers. A client preferring IPv6 may be sent to an address where Nginx is not listening or where a firewall blocks 443. Either configure the IPv6 listener and firewall consistently or remove the unusable address record. Also check that both listen 80 and listen [::]:80 (and their 443 equivalents) are intentional for your host.

Compare implementation choices before standardizing

Decision area Option A Option B What to verify
DNS routing Provider-managed wildcard record Explicit records for each hostname Wildcard synthesis rules, overrides, TTL behavior and support for both A and AAAA
Nginx ownership Self-managed configuration and reloads Configuration generated by a hosting or orchestration layer Whether your changes persist and which process owns the active server blocks
Transport HTTP only HTTPS with a 443 default server Redirect policy, certificate installation and renewal monitoring
Certificate scope Single-host certificates Wildcard certificate plus any apex or deeper names One-label wildcard limit and SAN coverage for every public hostname
Renewal Manual DNS TXT updates DNS API automation API permissions, propagation timing, secret protection and renewal alerts

A wildcard is convenient when many names share one service, but explicit DNS and server blocks provide tighter control when hosts have different ownership, security policies or backends. Decide whether an unknown hostname should serve a generic page, return an error, or be rejected before it reaches an application. Make that behavior intentional and test it after every configuration change.

Operational and security checks

  • Keep explicit application blocks separate from the fallback so a newly added wildcard rule cannot silently replace a production backend.
  • Do not treat the wildcard as authentication or tenant isolation. Any user who can direct a hostname at your address may be able to reach the fallback unless your application enforces its own access rules.
  • Log the requested host, status and upstream result. Host-based incidents are difficult to diagnose when all subdomains look identical in access logs.
  • Protect DNS API credentials used for DNS-01. Grant only the zone permissions required to create and remove validation TXT records.
  • Monitor certificate expiry and test renewal before the current certificate approaches its end date.
  • After adding a new explicit hostname, test both that hostname and a random undefined one. This catches accidental changes to precedence and default-server selection.

Reference configuration checklist

  • A wildcard DNS record points first-level subdomains to the Nginx address.
  • An apex record exists if the bare domain must work.
  • The intended fallback is marked default_server on every required listen port and address family.
  • The wildcard block uses server_name *.example.com, or .example.com when the apex and subdomains should share a name match.
  • Exact application names remain in their own server blocks.
  • The HTTPS certificate includes the wildcard and any apex or deeper names actually used.
  • Wildcard issuance uses DNS-01 and the _acme-challenge TXT update can be renewed automatically.
  • nginx -t passes before every reload.
  • Tests cover an explicit host, an undefined host, HTTP, HTTPS and (if published) IPv6.

With DNS resolving the names and Nginx selecting a deliberate default, arbitrary subdomains can share a safe baseline without disturbing dedicated sites. The key is to treat DNS records, Nginx precedence and certificate coverage as separate checks that must all pass.

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.

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.

DNSHTTPSNGINXTLSWeb server configurationWildcard subdomains

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.

Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

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.