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
Run Laravel queue workers with Supervisor
How to Run Laravel Queue Workers in Production with Supervisor
May 23, 2026
Nginx as a reverse proxy for a Node.js app on Ubuntu
How to Set Up Nginx as a Reverse Proxy for Node.js on Ubuntu
May 23, 2026
Install and configure Redis on Ubuntu for Laravel and WordPress
How to Install and Configure Redis on Ubuntu (for Laravel & WordPress)
May 23, 2026
Harden a fresh Ubuntu VPS with UFW, Fail2Ban, and SSH key auth
How to Harden a Fresh Ubuntu VPS: UFW + Fail2Ban + SSH Key Auth
May 23, 2026
Set up Let's Encrypt SSL with Certbot on Ubuntu
How to Set Up Let’s Encrypt SSL with Certbot on Ubuntu (Apache & Nginx)
May 23, 2026

You Might Also Like

Switch from LiteSpeed to Apache in WHM/cPanel
Server Management

How to Switch from LiteSpeed to Apache in WHM/cPanel

4 Min Read
Install MySQL on Ubuntu 22.04 — terminal with apt command and database cylinder icon
Server Management

How to Install MySQL on Ubuntu 22.04: Step-by-Step Guide

9 Min Read
Disable binary logging in MySQL or MariaDB
Server Management

How to Disable Binary Logging in MySQL or MariaDB

5 Min Read
Install the Apache web server on Ubuntu
Server Management

How to Install the Apache Web Server on Ubuntu

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