October 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 NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
VGSources
Blog

How to Redirect www to non-www in Nginx and Apache (with HTTPS)

Step-by-step Nginx and Apache configurations for redirecting www to a non-www HTTPS hostname while preserving deep links, query strings and TLS correctness.
WorldNginx and Apache Length10 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use a dedicated redirect endpoint for www.example.com, return a permanent 301 to https://example.com, and preserve the original request URI. In Nginx, create separate server blocks; in Apache, place a Redirect permanent directive in the virtual host for the non-canonical name. The HTTPS www endpoint must have a certificate that covers www.example.com, because TLS is negotiated before the redirect can be sent.

Choose one canonical hostname first

A site should publish one canonical hostname and send every alternate form to it. This guide uses the bare domain, example.com, as canonical and redirects www.example.com to it. The same pattern works in reverse if your chosen canonical name includes www; change the destination consistently in every block.

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.

Canonicalization keeps visitors, caches, bookmarks and crawlers on one hostname. It also gives you one place to serve the application instead of maintaining two independently reachable copies. A request such as http://www.example.com/docs/start?lang=en should finish at https://example.com/docs/start?lang=en, normally through one redirect.

How the redirect should work

  1. The client resolves the requested hostname and connects to the appropriate HTTP or HTTPS listener.
  2. The non-canonical listener recognizes www.example.com and returns 301 Moved Permanently.
  3. The Location header points directly to the canonical HTTPS URL and retains the request path and query string.
  4. The canonical HTTPS virtual host or server block serves the application without redirecting back to www.

Keeping the target as the final HTTPS URL avoids a chain such as http://www → http://bare → https://bare. A chain is harder to debug and causes extra requests. Do not configure rules that redirect the two hostnames to each other, and do not enable the www rule inside the canonical host.

Nginx: separate redirect and application server blocks

Prerequisites

  • Both DNS names point to the machine or load balancer handling the site.
  • The Nginx configuration defines www.example.com and example.com explicitly.
  • The certificate and private key used by the HTTPS www listener cover www.example.com; the canonical HTTPS listener needs coverage for example.com.
  • You can validate and reload Nginx using the deployment’s normal service procedure.

HTTP entry points

If HTTPS is mandatory, make both HTTP names redirect to the canonical HTTPS URL. The $request_uri variable contains the original path and arguments, so deep links and query strings are retained.

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

server {
    listen 80;
    server_name example.com;
    return 301 https://example.com$request_uri;
}

The first block handles the alternate hostname. The second handles an HTTP request that already uses the canonical hostname and upgrades it to HTTPS. If your policy allows HTTP on the canonical site, that second block could serve the application instead, but it should not send users back to www.

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

HTTPS entry points

HTTPS requires a certificate handshake before Nginx can issue an HTTP response. Therefore, the www redirect block must terminate TLS successfully even though it serves no application content.

server {
    listen 443 ssl;
    server_name www.example.com;

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

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

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;
    # application-specific location and proxy rules go here
}

Use certificate paths appropriate to your certificate issuer and installation. A certificate for only example.com does not automatically make https://www.example.com work; the certificate must include the www name as a subject alternative name or cover it with a suitable wildcard.

Why not combine this with an Nginx if rule?

Nginx’s simple return directive is the direct mechanism for a hostname redirect. A dedicated server block lets Nginx select the redirect based on server_name before application routing is involved. This is easier to reason about than putting conditional hostname logic in the canonical block, where an incomplete condition can create loops or affect requests that should be served.

What each Nginx directive does

Directive Purpose
listen 80 Accepts clear-text HTTP connections.
listen 443 ssl Accepts HTTPS connections and performs the TLS handshake.
server_name Associates a hostname with the server block selected for the request.
return 301 Sends a permanent redirect without invoking rewrite processing.
$request_uri Preserves the original path and query arguments.
root and location rules Serve or proxy the application only from the canonical HTTPS block.

Apache: preferred virtual-host redirect with mod_alias

HTTP virtual hosts

For a straightforward hostname redirect, Apache’s Redirect directive in a virtual host is simpler than a rewrite rule. Define a virtual host for each HTTP name. The prefix mapping preserves the path after the slash, and the request’s query string remains part of the redirected request.

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.
<VirtualHost *:80>
    ServerName www.example.com
    Redirect permanent / https://example.com/
</VirtualHost>

<VirtualHost *:80>
    ServerName example.com
    Redirect permanent / https://example.com/
</VirtualHost>

With this configuration, http://www.example.com/docs/start?lang=en is redirected to https://example.com/docs/start?lang=en. Keep the canonical HTTP virtual host if you want every HTTP request upgraded to HTTPS; otherwise it can contain the site’s normal HTTP configuration.

HTTPS virtual hosts

Create a certificate-bearing *:443 virtual host for www.example.com and put the same permanent redirect there. The canonical example.com HTTPS virtual host should contain the site’s document root or proxy configuration.

<VirtualHost *:443>
    ServerName www.example.com
    SSLEngine on
    SSLCertificateFile /path/to/fullchain.pem
    SSLCertificateKeyFile /path/to/privkey.pem

    Redirect permanent / https://example.com/
</VirtualHost>

<VirtualHost *:443>
    ServerName example.com
    SSLEngine on
    SSLCertificateFile /path/to/fullchain.pem
    SSLCertificateKeyFile /path/to/privkey.pem

    DocumentRoot /var/www/example
    # application-specific directives go here
</VirtualHost>

Use certificate directives and paths that match your Apache version and certificate deployment. The TLS certificate on the www virtual host must validate www.example.com before Apache can return the redirect.

Why Redirect is usually preferable here

This case is a mapping from one hostname to another, not a conditional rewrite of application URLs. A virtual-host-level Redirect permanent expresses that intent directly and keeps the rule out of the canonical site’s document root. It also avoids accidentally applying the redirect to requests for the canonical host.

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

Apache alternative: mod_rewrite when conditions are required

Use mod_rewrite when the redirect genuinely depends on conditions that Redirect cannot express. The condition below limits the rule to the alternate hostname.

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.example.com$ [NC]
RewriteRule ^ https://example.com%{REQUEST_URI} [R=301,L,NE]
  • RewriteCond matches only the intended www host, case-insensitively.
  • RewriteRule ^ matches the request path.
  • %{REQUEST_URI} carries the path and query portion into the destination.
  • R=301 makes the redirect permanent, and L stops further rewrite processing for that request.
  • NE prevents Apache from unnecessarily escaping characters already present in the target URL.

Place the rule in the www virtual host or in a context where it cannot run for the canonical host. If the same rule is active in both virtual hosts, the canonical request can be redirected repeatedly or transformed unexpectedly. For a simple virtual-host hostname change, retain the Redirect solution instead.

Preserving paths, query strings and URL characters

A homepage test alone is not enough. Redirect configuration must preserve deep links used by documentation, game pages, APIs and campaign URLs.

Original request Expected Location What must survive
http://www.example.com/ https://example.com/ Root path.
http://www.example.com/docs/start https://example.com/docs/start Nested path.
https://www.example.com/search?q=nginx&page=2 https://example.com/search?q=nginx&page=2 Path and query arguments.

Nginx preserves the complete request URI with $request_uri. Apache’s Redirect permanent / https://example.com/ maps the path beneath the slash to the destination and retains the query string. If you use a custom rewrite instead, test encoded characters and query parameters rather than assuming they will be handled identically by every rule context.

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.

Preventing HTTPS and hostname redirect loops

Use one direction for each decision

There are two independent decisions: whether the request uses HTTP or HTTPS, and whether it uses www or the bare name. Make both decisions point toward the same final URL, https://example.com. The canonical HTTPS host must serve content directly. It must not contain a rule that redirects to www, and the www rule must not point to an HTTP destination.

Account for TLS before HTTP

When a browser requests https://www.example.com, it checks the certificate before the server can send a 301. A missing certificate, a certificate that omits www, or a virtual-host selection error produces a TLS warning or handshake failure rather than a usable redirect. Install the certificate on the redirecting HTTPS endpoint and verify that the server presents the expected certificate for the requested name.

Be careful behind a reverse proxy

If a proxy or load balancer terminates TLS before forwarding to Nginx or Apache, make sure the origin receives the intended host and scheme information. Otherwise an origin rule may believe every request is HTTP and issue repeated HTTPS redirects. The exact header and trusted-proxy settings depend on the proxy, so validate the effective request scheme in that environment before enabling additional rewrite logic.

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

Validate safely before and after reload

Configuration checks

Run the server’s normal syntax validation before reloading. On many installations, the commands are:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
nginx -t
apachectl configtest

Use the command appropriate to your distribution and service layout. A successful syntax check does not prove that DNS, certificates or virtual-host selection are correct; those require HTTP and TLS requests.

Request matrix

  1. Reload or gracefully restart the server using your deployment’s standard procedure.
  2. Request http://www.example.com/ and confirm one 301 to https://example.com/.
  3. Request http://www.example.com/docs/start and verify that /docs/start is retained.
  4. Request a URL with a query string and verify every argument remains present.
  5. Request https://www.example.com/; confirm the TLS handshake succeeds and the response is one 301.
  6. Request https://example.com/docs/start; confirm the application returns its content without a redirect to www.
  7. Send a request with an unknown Host header and verify that an unintended default server does not expose the site.

For command-line inspection, include headers and disable automatic redirect following so you can see each hop:

curl -I http://www.example.com/docs/start?lang=en
curl -I https://www.example.com/docs/start?lang=en
curl -I https://example.com/docs/start?lang=en

The first two responses should show HTTP/1.1 301 (or the equivalent HTTP version) and a Location beginning with https://example.com. The final request should return the application’s normal success response rather than another redirect.

Troubleshooting common failures

The browser reports a certificate error on https://www

The redirect cannot run until TLS succeeds. Check that the certificate includes www.example.com, that the HTTPS virtual host is selected for that name, and that the full certificate chain is installed. Renew or replace the certificate before retesting the redirect.

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

The request loops between hosts or schemes

Inspect the complete redirect chain with curl -I. Search all Nginx server blocks, Apache virtual hosts and proxy rules for a rule that sends the canonical host back to www or that upgrades HTTPS repeatedly. Leave the redirect only on the alternate host and make the canonical HTTPS endpoint serve the application.

The path disappears or the query string changes

For Nginx, use $request_uri rather than a destination containing only the domain. For Apache, confirm the Redirect prefix is exactly / and test the actual virtual host receiving the request. In a rewrite rule, verify that %{REQUEST_URI} is present and that no later rule replaces the query string.

HTTP works but HTTPS www does not

HTTP and HTTPS are separate listeners and virtual-host selections. Define the *:443 or listen 443 ssl block explicitly, install a certificate for the www name, and ensure the TLS listener is reachable through the firewall or load balancer.

An unexpected site answers for an unknown hostname

An unmatched host can fall through to a default server. Define intentional default-server behavior and test an unrelated Host value. Do not rely on the application to reject names after the wrong virtual host has already exposed its content.

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

Nginx and Apache compared

Decision point Nginx Apache
Primary configuration location Dedicated server block selected by server_name. Dedicated virtual host selected by ServerName.
Simple redirect directive return 301 https://example.com$request_uri; Redirect permanent / https://example.com/
Conditional logic Use separate server blocks; avoid an unnecessary combined if for this case. Use mod_rewrite only when conditions are genuinely needed.
Path and query preservation $request_uri retains the original URI and arguments. Redirect prefix mapping retains the path and query; rewrite rules should use %{REQUEST_URI}.
HTTPS requirement The www SSL server block must present a certificate covering www. The www *:443 virtual host must complete TLS before redirecting.
Preferred chain One 301 directly to canonical HTTPS. One 301 directly to canonical HTTPS.
Operational check Run Nginx syntax validation, reload, then test both listeners. Run Apache configuration validation, reload, then test both listeners.

Deployment checklist

  • Decide whether the bare or www hostname is canonical and use that choice everywhere.
  • Point both DNS names at the system that will issue the redirect and serve the application.
  • Create an HTTP redirect for www and, when required, an HTTP-to-HTTPS redirect for the canonical name.
  • Create a separate HTTPS redirect endpoint for www with certificate coverage for that hostname.
  • Keep application content only on the canonical HTTPS endpoint.
  • Use a permanent 301 and preserve the original URI.
  • Validate syntax before reload and reload gracefully.
  • Test the homepage, a deep path, a query string, both HTTP and HTTPS, and an unknown host.
  • Confirm the final canonical response serves content and never redirects back to www.

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