Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon 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 Now×
FREEDOM251

Freedom251 › Blog › HTTPS

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

By Freedom251 Team · · 12 min read

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

Put every source hostname in a dedicated Nginx server block and return a permanent redirect to the single canonical HTTPS hostname. For example, www.example-one.com, www.example-two.com, and www.example-three.com can all send visitors to https://example.com while preserving the original path and query string.

The essential directive is return 301 https://example.com$request_uri;. Use a separate block for the canonical site, configure certificates for any HTTPS source names, test with a temporary redirect while rolling out if necessary, and switch to 301 only after every hostname behaves correctly.

As an Amazon Associate I earn from qualifying purchases.

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.

The canonical Nginx pattern

Nginx selects a virtual-server block by matching the request’s host against server_name. A finite set of known aliases should therefore be listed explicitly in one redirect block. The block does not proxy a request, serve files, or run application logic; it only returns the new 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;
}

server {
    listen 443 ssl;
    server_name example.com;

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

    root /var/www/example;
    # Or use proxy_pass, FastCGI, or your normal application configuration.
}

The first block handles plain HTTP requests for all three www names. The second block is the actual non-www site. Replace the example names, certificate paths, and content configuration with your own values. Every source hostname must resolve to the Nginx server; otherwise the request will never reach this configuration.

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

$request_uri is the complete original URI, including the path and arguments. A request for /docs/start?ref=nav&lang=en therefore becomes https://example.com/docs/start?ref=nav&lang=en. Do not replace it with a hard-coded slash if deep links and query parameters must survive the redirect.

Why a dedicated redirect server is preferable

Nginx supports conditional rewrites, but a simple host canonicalization does not need conditional logic. A dedicated server block makes the mapping visible, limits it to the intended names, and lets Nginx handle the redirect before application processing. It also avoids embedding host tests in a general-purpose site block, where a later configuration change can accidentally create a loop or redirect the wrong domain.

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

The return directive is valid in the server context and can emit a 301, 302, or 307 response directly. For a permanent canonical-host change, 301 communicates that the old hostname should no longer be used. During initial deployment, a temporary status can make recovery easier because browsers and intermediary caches are less likely to retain the mapping before it has been verified.

Build the configuration step by step

1. Inventory the hostnames

Write down every source name that should redirect and the one destination name that should serve content. In this example the source set is www.example-one.com, www.example-two.com, and www.example-three.com; the destination is example.com. Keep the list finite and explicit when you know it in advance. Do not include the destination hostname in the redirect block, or the canonical site can redirect to itself.

2. Add the HTTP redirect block

Create a server block listening on port 80. List all source names on one server_name line (line wrapping is also valid) 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;
}

This single response performs both host canonicalization and the HTTP-to-HTTPS upgrade. It does not first send the visitor to an HTTPS version of the www name.

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

3. Add the canonical HTTPS site

Give the destination its own HTTPS block. It must contain the certificate and key for the non-www name and your ordinary static-file, proxy, or application settings.

server {
    listen 443 ssl;
    server_name example.com;

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

    root /var/www/example;
    index index.html;
}

Keeping this block separate is important: the canonical host should return the application response, not another redirect. If the site is reverse-proxied, replace the root and index lines with the existing proxy configuration.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter | USB C Dongle with 90W Max Power Delivery, 3×5Gbps USB A Data Ports, for MacBook, Dell, and More (Charger Not Included)
  • 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. Add an HTTPS redirect block for the source names

Clients can request an HTTPS www URL directly, so Nginx must also have a port-443 block for those names. It can return the same destination URL:

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

    ssl_certificate /etc/nginx/ssl/www-example/fullchain.pem;
    ssl_certificate_key /etc/nginx/ssl/www-example/privkey.pem;

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

The certificate directives are required before Nginx can send an HTTP redirect over TLS. The certificate presented during the handshake must cover each source name that clients use. If a visitor reaches https://www.example-two.com and that name is absent from the certificate, the browser can stop with a certificate warning before it receives the 301 response.

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

5. Validate and reload

  1. Run nginx -t and fix every syntax or certificate-path error it reports.
  2. Reload the service using the process supervisor used by your system, such as systemctl reload nginx. A reload applies the new configuration without stopping existing workers.
  3. Test each source hostname over both protocols, then test a root URL, a deep path, and a URL containing a query string.

Do not move to a permanent redirect until the destination, path, query string, and certificate behavior are correct for every name.

Preserving paths and query strings

The variable $request_uri contains the original path and its arguments. Appending it to the fixed destination host preserves links such as:

https://www.example-one.com/account/settings
https://www.example-two.com/products/widget?campaign=spring&ref=email

They redirect respectively to:

https://example.com/account/settings
https://example.com/products/widget?campaign=spring&ref=email

This matters for bookmarks, search-engine links, analytics parameters, API endpoints, and links embedded in emails. A redirect that ends at only https://example.com discards the requested location. A rewrite that constructs a new path manually can also lose arguments or alter URL encoding.

Use the destination host as a literal value when all aliases have one known canonical domain. That makes the policy auditable and prevents an unintended host value from being copied into the Location header.

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

HTTP and HTTPS: choose the number of hops

There are two common deployment strategies. The direct strategy sends an HTTP or HTTPS request for any source name straight to the canonical HTTPS URL. A two-hop strategy first upgrades the protocol while retaining the source host and then changes the host on a second response.

Strategy Response sequence Advantages Requirements and trade-offs
Direct canonical redirect http://www.example-one.com/path → https://example.com/path Usually one response; shortest path to the final URL; one policy to audit. Every HTTPS source name still needs a valid certificate because a direct HTTPS request performs TLS before Nginx can redirect it.
Two-hop normalization http://www.example-one.com/path → https://www.example-one.com/path → https://example.com/path Separates protocol enforcement from host canonicalization and can fit an existing staged policy. Two responses add latency and require a working HTTPS configuration and certificate for each source name.

For most new mappings, the direct form is simpler. It gives the browser the final canonical URL immediately and avoids a second round trip. A two-hop arrangement is valid when another part of the infrastructure already owns the first upgrade or when policy requires the source hostname to remain visible for an intermediate step.

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.

Certificate planning for source hostnames

HTTP redirects do not require a certificate because the connection is unencrypted. HTTPS redirects are different: the TLS handshake happens before Nginx can evaluate the HTTP request and issue a 301. Consequently, every source name exposed on port 443 must be covered by the certificate selected for that server block.

Plan certificate coverage for all aliases, not only the canonical name. If the certificate is valid for example.com but not www.example-one.com, an HTTPS request to the latter can fail before the redirect. Keep the certificate and key directives in the source HTTPS block, and keep the canonical certificate in the destination block when the two sets differ.

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.

If you do not intend to accept HTTPS connections for a particular alias, do not advertise that URL to users or links. Clients that try it will still need a certificate during TLS negotiation; an HTTP-only redirect block cannot solve a certificate mismatch on port 443.

Exact names, wildcards, and regular expressions

Nginx accepts exact hostnames, wildcard names, and regular-expression names. Choose the narrowest form that represents your actual policy.

Matching form Example Best use Auditability and cost
Explicit names server_name www.alpha.example www.beta.example www.gamma.example; A known, finite collection of aliases. Highest auditability. Frequently used exact names are efficiently defined and easy to review.
Wildcard server_name *.example.com; An intentionally broad policy covering a predictable subdomain pattern. Broader scope; verify that every matched subdomain is safe to redirect before enabling it.
Regular expression server_name ~^www.(.+).example.com$; A deliberately pattern-based set that cannot be represented clearly with a finite list or wildcard. Regular expressions are tested sequentially and are slower and less scalable than exact or wildcard matching. They can also catch names you did not intend to include.

Do not use a wildcard or regular expression merely to save a few characters when the source list is short. An explicit list documents the redirect contract and reduces the chance that a newly created subdomain is redirected without an owner reviewing the effect. If the set is intentionally broad, document the scope and test representative names that should match and should not match.

Handling unknown Host headers with a catch-all

Named redirect blocks should handle the aliases you have approved. Requests whose host does not match an intended site can be handled separately with a default server. A catch-all policy prevents an unrelated or mistyped host from accidentally reaching the canonical application.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
server {
    listen 80 default_server;
    server_name _;
    return 404;
}

The underscore is a conventional placeholder for a block selected as the default; it is not a hostname that users should visit. You can return another controlled response or an intentional redirect if that matches your operational policy. Treat this block as a policy for unknown hosts, not as a substitute for listing the known www names. A named source can be overlooked, and relying on the default block hides that configuration mistake rather than documenting the mapping.

If you expose a default HTTPS listener, remember that TLS certificate selection still occurs before the HTTP response. Configure a certificate appropriate for the names that may reach that listener, or avoid presenting an HTTPS endpoint for names you have not planned to serve.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray | Data transfer & Fast charging for MacBook, iPhone 17/16/15, iPad, Samsung Galaxy, Apple Watch
  • 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

Choosing the redirect status

301 for a confirmed permanent move

Use 301 when the aliases are permanently replaced by the non-www hostname. Browsers, proxies, and other intermediaries may cache a 301, so changing the policy later can require clearing caches or waiting for old responses to expire.

302 or 307 during rollout

A temporary 302 or 307 is useful while you verify certificates, paths, query strings, and application behavior. Nginx supports these status codes with the same return directive. A 307 is designed to preserve the request method, which can matter for non-GET requests; a 302 is commonly used for ordinary browser checks. Once the mapping is proven and intended to persist, change the response to 301.

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

Do not treat a temporary status as a fix for an incorrect destination. It only changes caching and permanence; the host matching, TLS setup, and URI preservation still need to be correct.

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

Testing every source hostname

Test from a client that can resolve the names to the server. The -I option asks for response headers without downloading the page.

curl -I http://www.example-one.com/
curl -I http://www.example-two.com/guides/start?ref=nav&lang=en
curl -I https://www.example-three.com/products/widget
curl -I https://example.com/products/widget

For each source request, confirm that the status is the one you configured and that the Location header is exactly the canonical HTTPS URL with the same path and arguments. The destination request should return the application or static-site response rather than another redirect.

Repeat the checks for every listed alias. A typo in one server_name entry can leave only that domain on a different virtual server, making a configuration appear correct when tested against just one name. Include at least these cases:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • The root path, such as /.
  • A deep path, such as /docs/start or an application route.
  • A query string containing more than one argument.
  • Both HTTP and HTTPS for every source name that is meant to accept both protocols.
  • The canonical HTTPS hostname, to ensure it serves content and does not loop.

To observe the final result in a controlled check, use curl -I -L and inspect each response in the chain. During rollout, avoid relying only on a browser: a cached 301 can make a corrected configuration look unchanged.

Troubleshooting common failures

Nginx serves the application instead of redirecting

The request reached a different server block. Check that the exact host is spelled correctly in server_name, that the block listens on the port being tested, and that another configuration file is not claiming the same name. Run nginx -t after correcting the file and reload Nginx. Test with the hostname in the request rather than an IP address, because host matching depends on the requested name.

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

The browser reports a certificate error on an HTTPS source URL

The redirect cannot be delivered until TLS succeeds. Add the source hostname to the certificate coverage and ensure the certificate and key configured in the port-443 source block are the intended files. Confirm the block is selected for that name and port. An HTTP certificate cannot be used as a workaround for a client that explicitly requested HTTPS.

The path or query string disappears

Inspect the return line. It should append $request_uri directly to the canonical host. A hard-coded destination such as https://example.com/ intentionally drops the original location. Re-test with a deep path and multiple query arguments, because a root-only test will not reveal this error.

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

The canonical site loops back to itself

Make sure example.com is not included in the source redirect block and that its own server block serves the site. A loop can also occur when a broad wildcard or regular expression matches the canonical name. Narrow the pattern or use explicit source names, then test the destination URL without following redirects to identify which block is returning the next response.

Changes seem to have no effect

First run nginx -t; a failed test means the old configuration remains active. After a successful test, reload Nginx rather than editing files without applying them. If the response is still a previously cached 301, test with curl from a clean client or use a temporary status while validating the new mapping.

An unexpected hostname is redirected

Review wildcard and regular-expression entries and the default-server policy. A broad matcher may include more names than intended. Replace it with an explicit list when the approved set is finite, or tighten the pattern so that unrelated subdomains are not sent to the canonical site.

A complete multi-domain example

The following configuration combines the three listeners involved in a typical direct, one-hop setup. The HTTP source block upgrades and canonicalizes in one response. The HTTPS source block supplies certificates and performs the same canonicalization after TLS. The final block serves the non-www site.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
server {
    listen 80;
    server_name www.example-one.com www.example-two.com www.example-three.com;
    return 301 https://example.com$request_uri;
}

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

    ssl_certificate /etc/nginx/ssl/www-example/fullchain.pem;
    ssl_certificate_key /etc/nginx/ssl/www-example/privkey.pem;

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

server {
    listen 443 ssl;
    server_name example.com;

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

    root /var/www/example;
    index index.html;
}

Place the blocks in the appropriate enabled Nginx configuration, adapt the certificate paths and content settings, validate with nginx -t, reload, and test every source name. The key design decisions are the explicit source list, the fixed canonical destination, the preserved $request_uri, and certificate coverage for HTTPS aliases.

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.

HTTPSNGINXserver administrationURL redirectsweb servers

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