Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober 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 PC×
Skip to content
VGSources
Blog

How to Redirect Multiple www Domains to One Non-www Domain in Nginx

Use explicit Nginx server_name lists and dedicated return 301 blocks to send multiple www domains to one non-www HTTPS host without losing deep paths or query strings.
WorldNginx Length9 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Put every source hostname in a dedicated Nginx redirect server block and return the canonical HTTPS URL with $request_uri:

server {
    listen 80;
    server_name www.example-one.com www.example-two.com www.example-three.com;
    return 301 https://example.com$request_uri;
}

Use a corresponding listen 443 ssl block for the same www names when HTTPS requests are possible, and keep example.com in its own application or proxy block. This arrangement preserves the original path and query string, avoids conditional rewrite logic, and makes the list of canonicalization rules easy to audit.

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.

What the redirect does

Suppose a visitor requests http://www.example-two.com/store/item-7?color=red. Nginx selects the server block whose server_name matches www.example-two.com, then sends a permanent redirect:

HTTP/1.1 301 Moved Permanently
Location: https://example.com/store/item-7?color=red

The browser follows that location and the canonical, non-www site handles the request. The $request_uri variable contains the original URI, including its arguments, so appending it retains both the path and query string. Do not replace it with only a hard-coded slash if deep links must continue to work.

#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter | 4Pack Type C Female to A Male Cable Converter for Apple Duo 17 16 15 14 Plus,iWatch Watch 12 11 10,iPad 9 8 Air,Airpods 5 4
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

A dedicated redirect server is preferable to an if-based hostname test for this simple job. NGINX’s “Converting rewrite rules” guidance describes defining a separate server for a redirecting hostname as the correct approach rather than using cumbersome conditional logic.

Build the configuration

1. List the source and canonical names

Write down every hostname that should converge on the canonical site. For a finite set, use exact names:

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.
  • www.example-one.com
  • www.example-two.com
  • www.example-three.com

Decide whether the canonical destination is always HTTPS. The examples below use https://example.com. Replace the example names with your real domains and keep the spelling consistent in DNS, certificates and Nginx.

2. Add the HTTP redirect server

Create a server block that listens on port 80 and contains only the source names and the redirect:

server {
    listen 80;
    server_name www.example-one.com www.example-two.com www.example-three.com;

    return 301 https://example.com$request_uri;
}

Because the destination hostname is written explicitly, every listed source goes to the same canonical host. The request path and arguments are copied from the original request.

3. Handle HTTPS requests for the www names

An HTTPS request cannot reach the HTTP redirect block. TLS negotiation happens before Nginx can send an HTTP response, so each HTTPS source hostname needs certificate coverage. Add a separate SSL redirect block:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
server {
    listen 443 ssl;
    server_name www.example-one.com www.example-two.com www.example-three.com;

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

    return 301 https://example.com$request_uri;
}

The certificate paths above are examples. Your certificate set must cover all names clients can request, either through one certificate containing the names or through the certificate arrangement appropriate to your deployment. The redirect itself is still the same one-line return directive.

Rank #2
Sale
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

4. Give the canonical host its own HTTPS block

Keep the non-www site separate from the redirect blocks. Put your normal static-root, application or reverse-proxy settings there:

server {
    listen 443 ssl;
    server_name example.com;

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

    root /var/www/example;
    # Or use your normal application configuration, for example:
    # location / {
    #     proxy_pass http://127.0.0.1:3000;
    # }
}

Do not put the canonical application and the source-host redirect in one ambiguous block. Separate blocks make it clear which host serves content and which hosts only redirect.

5. Upgrade canonical HTTP when required

If visitors can request http://example.com, add a port-80 block for the canonical name as well:

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

    return 301 https://example.com$request_uri;
}

This handles the protocol upgrade for the canonical hostname. The source www block can still redirect directly to the final HTTPS, non-www URL, avoiding an unnecessary intermediate response.

Complete example for three domains

The following layout covers HTTP and HTTPS requests for three source names, upgrades the canonical HTTP site, and serves the canonical HTTPS application:

# HTTP www hosts: direct to the final canonical URL
server {
    listen 80;
    server_name www.example-one.com www.example-two.com www.example-three.com;

    return 301 https://example.com$request_uri;
}

# HTTPS www hosts: TLS must succeed before this redirect is sent
server {
    listen 443 ssl;
    server_name www.example-one.com www.example-two.com www.example-three.com;

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

    return 301 https://example.com$request_uri;
}

# Canonical HTTP: upgrade protocol
server {
    listen 80;
    server_name example.com;

    return 301 https://example.com$request_uri;
}

# Canonical HTTPS application
server {
    listen 443 ssl;
    server_name example.com;

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

    root /var/www/example;
}

Use your existing certificate, root and proxy settings in place of the illustrative values. The important parts of the canonicalization are the explicit server_name lists and the return 301 https://example.com$request_uri; lines.

Why server_name matters

Nginx uses the request’s host name to choose a virtual-server block. A name can be written as an exact name, a wildcard, or a regular expression. When the set of domains is known, explicit names are the most auditable choice: a reviewer can see every hostname that will redirect and an accidental domain is less likely to be included.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter | 85W Max PD, 2 USB 3.0 & 1 USBC Data Ports, SD/TF Card Reader, for Laptops/Mac and Other Type C Devices (Charger Not Included)
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Exact names

server_name www.alpha.example www.beta.example www.gamma.example;
  • Scope: only the listed names.
  • Auditability: high; additions and removals are visible in one line.
  • Best fit: a known collection of domains that all belong to the same canonical site.

Wildcard names

server_name *.example.net;

A wildcard is useful when an intentionally broad namespace should follow one policy. Confirm exactly which names your wildcard covers before deploying it. Do not use a broad pattern merely to avoid maintaining a short, known list.

Regular expressions

server_name ~^www.(?[a-z0-9-]+).example.net$;

Regular expressions can express a dynamic naming rule, but Nginx tests regex names sequentially. The documentation notes that they are slower and less scalable than exact or wildcard matching. Use one only when the broader matching behavior is deliberate, documented and tested; otherwise prefer explicit names.

Matching form Use when Operational trade-off
Exact names The source domain set is finite and known. Most transparent to review and least likely to redirect an unintended host.
Wildcard An entire, intentionally managed namespace shares the policy. Shorter configuration, but the scope is broader and must be checked carefully.
Regular expression The names follow a genuine pattern that cannot be expressed clearly with exact or wildcard names. Flexible, but regex names are evaluated sequentially and cost more to match.

Preserving paths and query strings

Use $request_uri in the destination:

return 301 https://example.com$request_uri;

For a request such as /news/episode-4?platform=pc&sort=new, the resulting location remains https://example.com/news/episode-4?platform=pc&sort=new. This matters for bookmarked pages, search links, campaign parameters, API endpoints and any application route below the home page.

Do not add a second slash accidentally. The destination should be the host followed immediately by $request_uri; Nginx already receives the leading slash as part of the URI. If the incoming request has no query string, none is added to the redirect.

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

One-hop versus two-hop canonicalization

There are two common policies when both HTTP and HTTPS are in use. Choose one intentionally rather than allowing the final URL to depend on which source protocol the visitor used.

Policy Typical response sequence Requirements and trade-offs
Direct canonical HTTPS http://www.example.com/path → https://example.com/path in one redirect. The HTTP source block is simple; an HTTPS source block and certificate coverage are still required for visitors who start with HTTPS.
Protocol first, host second http://www.example.com/path → https://www.example.com/path → https://example.com/path. Two responses and an extra round trip. The intermediate HTTPS source host must be configured and certified.

A direct source-to-canonical HTTPS redirect usually gives the desired final URL in one response. It does not remove the TLS requirement for an HTTPS request to a www source: the client still has to establish TLS for that hostname before Nginx can return the redirect.

Choosing a redirect status

301 for a confirmed permanent move

Use 301 when the hostname change is permanent:

return 301 https://example.com$request_uri;

Browsers and intermediaries may cache a permanent result, so check the mapping carefully before making it public.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

302 or 307 during rollout

Use a temporary 302 or 307 while validating a new mapping if you want to reduce the risk of a cached permanent redirect during testing. Once the canonical destination is confirmed, change the response to 301. Keep the same destination and $request_uri handling unless your test specifically requires a different behavior.

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

Unknown-host and default-server behavior

A request whose host does not match one of your intended site names can be handled by a deliberate default server. Nginx allows a default_server listener and a conventional catch-all name such as _:

server {
    listen 80 default_server;
    server_name _;

    return 404;
}

This is a separate policy for unknown hosts. It should not replace the explicit mappings for your named www domains. Decide whether an unmatched request should receive a controlled error, a generic landing page or another policy appropriate to your environment, and configure that behavior explicitly on the default listener.

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

Validate and deploy safely

Check the syntax before reloading

  1. Save the server blocks in the site configuration included by your main Nginx configuration.
  2. Run nginx -t. Continue only when the test reports that the configuration syntax is valid and the test is successful.
  3. Reload Nginx using your operating system’s service manager, such as systemctl reload nginx, so existing connections can finish while the new configuration is adopted.

Test every source hostname

Check representative requests for each source domain over both protocols that you intend to support:

curl -I http://www.example-one.com/
curl -I http://www.example-two.com/game/level-2?mode=hard
curl -I http://www.example-three.com/news?id=42
curl -I https://www.example-one.com/
curl -I https://www.example-two.com/game/level-2?mode=hard
curl -I https://www.example-three.com/news?id=42

For each response, verify:

  • The status is the temporary or permanent code you selected.
  • The Location header uses the one canonical, non-www HTTPS hostname.
  • The deep path is unchanged.
  • The query string is unchanged and appears only once.
  • The canonical URL serves the expected application rather than redirecting back to a source hostname.

Also test the canonical HTTP hostname if you added a protocol-upgrade block:

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.
curl -I http://example.com/game/level-2?mode=hard

Use a browser only after command-line checks pass; browsers can retain cached 301 results and make a configuration mistake appear fixed or persist after it has been corrected.

Troubleshooting common failures

The request reaches the wrong site

Check that the hostname is spelled in the intended server_name list and that the configuration file is actually included. Run nginx -t after every edit and confirm that no other server block is unintentionally handling the same listener and name.

Best Value
Sale
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display | 85W Max PD, 1 Powered USB-C 5Gbps & 2 Powered USB-A 3.0 5Gbps Data Ports, for MacBook Pro, MacBook Air, Dell and More (Black)
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

HTTP redirects, but HTTPS shows a certificate warning

The HTTPS connection is failing before the redirect can be returned. Install or select a certificate that covers the requested www name, place the certificate directives in the listen 443 ssl source block, then reload and test again. A redirect cannot compensate for missing TLS coverage.

The path disappears

Inspect the return line. It should end with $request_uri, not only the canonical host or a hard-coded slash. Retest with a deep URL rather than just the home page.

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

The query string is missing or duplicated

Use $request_uri exactly once in the destination and avoid manually appending a second question mark. Test a URL containing multiple parameters, for example ?mode=hard&platform=pc, and inspect the Location header with curl -I.

A redirect loop appears

Verify that the canonical HTTPS block serves content instead of redirecting example.com back to a www name. Check that the source blocks list only source names and that any application-level canonicalization agrees with Nginx. Follow the chain with a header request and stop when the first repeated URL appears.

Only some source domains redirect

Compare the failing name with the explicit server_name list, DNS records and certificate names. Every finite source hostname must be listed in the HTTP block and, when HTTPS is supported, in the HTTPS SSL block as well.

The change works locally but not publicly

Confirm that DNS for each source hostname points to the Nginx instance receiving the request and that the listener is reachable on the intended port. Then repeat the HTTP and HTTPS checks from a network that resolves the public records.

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

Operational checklist

  • Canonical destination is written as one exact HTTPS hostname.
  • Every intended source www name appears explicitly when the set is finite.
  • HTTP source names have a listen 80 redirect block.
  • HTTPS source names have a listen 443 ssl redirect block and certificate coverage.
  • The canonical host has its own HTTPS application block.
  • $request_uri is appended to preserve paths and query strings.
  • The selected status code matches the rollout stage: temporary while testing, 301 after confirmation.
  • Unknown hosts have an intentional default_server policy.
  • nginx -t succeeds before reload.
  • Root, deep-path and query-string requests are checked for every source hostname over every supported protocol.

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