How7o
  • Home
  • Tools
  • Prank Screens
  • Learn
  • Blog
  • Contact
Reading: How to Redirect www to non-www (or vice versa) in Nginx
Share
How7oHow7o
Font ResizerAa
  • OS
Search
  • Home
  • Tools
  • Prank Screens
  • Learn
  • Blog
  • Contact
Follow US
© 2024–2026 How7o. All rights reserved.
How7o > Free Laravel, PHP, WordPress & Server Tutorials > Server Management > How to Redirect www to non-www (or vice versa) in Nginx
Server Management

How to Redirect www to non-www (or vice versa) in Nginx

how7o
By how7o
Last updated: May 22, 2026
5 Min Read
Nginx redirect www to non-www or vice versa
SHARE

To redirect non-www to www (or www to non-www) in Nginx, use a dedicated server block for the alternate hostname that returns a 301 to the canonical one. Use $request_uri to preserve the path and query string, and prefer return 301 over rewrite for performance and clarity.

Contents
  • Redirect non-www to www
  • Redirect www to non-www
  • Multiple domains in one block
  • HTTPS — the full four-block pattern
  • Test before reloading
  • Frequently asked questions
  • Related guides
  • References

Last verified: 2026-05-17 on Nginx 1.24. Originally published 2023-02-04, rewritten and updated 2026-05-17.

Redirect non-www to www

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

server {
    listen 80;
    server_name www.example.com;
    # ... your real configuration
}

The first block catches requests for example.com and sends a 301 to www.example.com, preserving the path via $request_uri and the protocol via $scheme.

Nginx www / non-www redirect — separate server blocks, return 301, $request_uri, multi-domain regex

Redirect www to non-www

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

server {
    listen 80;
    server_name example.com;
    # ... your real configuration
}

Multiple domains in one block

# Force non-www -> www across every domain on this server
server {
    listen 80;
    server_name "~^(?!www\.).*";
    return 301 $scheme://www.$host$request_uri;
}

# Force www -> non-www across every domain
server {
    listen 80;
    server_name "~^www\.(.*)$";
    return 301 $scheme://$1$request_uri;
}

The regex form uses server_name with a regular expression so it catches any domain matching the pattern. $host contains the incoming hostname; $1 captures the part after www..

HTTPS — the full four-block pattern

# HTTP non-www -> HTTPS non-www (canonical)
server {
    listen 80;
    server_name example.com;
    return 301 https://example.com$request_uri;
}

# HTTP www -> HTTPS non-www
server {
    listen 80;
    server_name www.example.com;
    return 301 https://example.com$request_uri;
}

# HTTPS www -> HTTPS non-www
server {
    listen 443 ssl http2;
    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;
}

# Canonical site
server {
    listen 443 ssl http2;
    server_name example.com;
    ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    # ... your real configuration
}

Three of the four blocks just redirect; only the canonical one serves real content. The HTTPS-www block needs a TLS cert that covers www.example.com — Let’s Encrypt handles this if you include both in the same certificate (Certbot’s -d example.com -d www.example.com).

Test before reloading

sudo nginx -t                       # validate config syntax
sudo systemctl reload nginx         # apply without dropping connections

# Verify the redirect
curl -I https://example.com/some/path
curl -I https://www.example.com/some/path

Each curl -I should return HTTP/2 301 with a Location header pointing at the canonical URL (and preserving the path).

Frequently asked questions

Why pick www over non-www (or vice versa)?

Either is fine technically — pick one and redirect the other to it. The choice affects analytics and SEO mostly: split traffic between www and bare versions can dilute backlink credit and confuse session metrics. Pick whichever your domain already appears as in most external links and your social profiles; redirect the other.

Will the redirect work for HTTPS too?

The examples above use listen 80. For HTTPS you need a parallel server block listening on 443 with TLS certs. Most production setups have four blocks: HTTP → HTTPS (force-TLS), HTTP www → HTTPS canonical, HTTPS www → HTTPS canonical, plus the canonical block itself. Certbot’s --nginx plugin can wire most of this up automatically.

Should I use if ($host = '...') or separate server blocks?

Separate server blocks. Nginx’s own documentation warns that if inside a server context is fragile and can interact badly with other directives — see “If Is Evil” on nginx.org. The combined-server-name if pattern works in practice for simple redirects but separate blocks are cleaner and faster.

Why return 301 instead of rewrite?

return is faster and more explicit. rewrite ... permanent works but executes regex unconditionally; return 301 emits the response without rewriting. For a static destination URL, return 301 $scheme://canonical.tld$request_uri is the canonical form.

Related guides

  • How to Configure Nginx for a Subdirectory
  • How to Fix Nginx FastCGI “Connection Reset by Peer” Errors
  • How to Install the Apache Web Server on Ubuntu

References

Nginx server_name: nginx.org/en/docs/http/server_names.html. Nginx “If Is Evil”: nginx.com/resources/wiki/start/topics/depth/ifisevil. Let’s Encrypt + Nginx: certbot.eff.org/instructions?ws=nginx.

TAGGED:configurationLinuxNginxredirects

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
[mc4wp_form]
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Share This Article
Facebook Copy Link Print
Previous Article Prevent tab key from focusing on a link with tabindex=-1 How to Skip a Link When Pressing Tab (tabindex=-1)
Next Article Run JS code on URL hash change with the hashchange event How to Run Code on URL Hash Change in JavaScript
Leave a Comment

Leave a Reply Cancel reply

You must be logged in to post a comment.

FacebookLike
XFollow
PinterestPin
InstagramFollow
Most Popular
Laravel Eloquent ORM — a model class mapping to a database table with query methods
Laravel Eloquent ORM: The Complete Guide to Querying Your Database
June 16, 2026
Set vi as the default editor in Ubuntu — a terminal opening the vim editor
How to Set vi (Vim) as the Default Editor in Ubuntu
June 8, 2026
rsync says ALL DONE but files are missing — a terminal showing ALL DONE next to an empty folder
rsync Says “ALL DONE” but Files Are Missing: How to Verify
June 8, 2026
Migrate a website to a new server with rsync — files copying from an old server to a new one over SSH
How to Migrate a Website to a New Server With rsync
June 8, 2026
Bun runtime — faster JS toolkit replacing npm in Laravel projects
How to Install Bun Runtime on Ubuntu (And Use It in a Laravel Project)
May 24, 2026

You Might Also Like

Run a Node.js application from a Windows .bat file
OS

How to Run a Node.js Application from a Windows .bat File

5 Min Read
Get a remote file size from URL in PHP with get_headers
Web Development

How to Get a Remote File’s Size from a URL in PHP

4 Min Read
MySQL primary and replica database cylinders connected by replication arrows
Server Management

How to Set Up MySQL Primary-Replica Replication on Ubuntu (Production Guide)

10 Min Read
Cloudflare Tunnel — outbound-only connection from server, no inbound port forward
Server Management

How to Install Cloudflare Tunnel on Ubuntu (Expose Local Services, No Port Forwarding)

9 Min Read
How7o

We provide tips, tricks, and advice for improving websites and doing better search.

Tools

  • Age Calculator
  • Word Counter
  • Image Upscaler
  • Password Generator
  • QR Code Generator
  • See all tools→

Pranks

  • Fake Blue Screen Prank
  • Hacker Typer
  • Fake iMessage Generator
  • Windows XP Crash Prank
  • Windows 11 Update Prank
  • See all prank screens →

Company

  • About Us
  • Blog
  • Contact
  • Privacy Policy
  • Terms of Service
  • Sitemap
© 2024–2026 How7o. All rights reserved.
Welcome Back!

Sign in to your account

Username or Email Address
Password

Lost your password?