Nginx makes it straightforward to redirect traffic between www and non-www versions of your domain, ensuring all visitors land on a single canonical URL. This consistency prevents duplicate content issues in search engines, consolidates link equity, and provides a cleaner user experience. Whether you prefer www.example.com or example.com as your primary domain, this guide walks through both redirect directions with tested configurations for HTTP and HTTPS.
By the end of this guide, you will have a working Nginx configuration that permanently redirects all traffic to your preferred domain format, verified with command-line testing.
Prerequisites
Before configuring redirects, ensure your server meets these requirements:
- Nginx installed and running: If you need to install Nginx, see our guides for installing Nginx on Ubuntu, Debian, or Fedora.
- DNS configured for both domains: Both
example.comandwww.example.commust resolve to your server’s IP address. Check withdig example.comanddig www.example.com. - An existing server block: You should have a working Nginx configuration serving your site before adding redirects.
- For HTTPS redirects: SSL certificates covering both domain formats. Let’s Encrypt certificates can include both as Subject Alternative Names (SANs).
Understanding 301 Permanent Redirects
When redirecting between www and non-www, you should always use a 301 (permanent) redirect. This tells browsers and search engines that the change is permanent, which in turn:
- Transfers SEO value from the old URL to the canonical URL
- Instructs browsers to cache the redirect, reducing future server requests
- Consolidates analytics and link tracking under a single domain
Nginx provides two methods for implementing redirects: the return directive and the rewrite directive. For simple domain redirects, return 301 is preferred because it processes faster and requires no regular expression evaluation. As a result, this guide focuses on the return method for most examples.
Where to Place Redirect Configurations
Nginx configuration file locations vary by installation method:
- Distribution packages (Debian/Ubuntu): Use
/etc/nginx/sites-available/with symlinks to/etc/nginx/sites-enabled/ - nginx.org packages or source builds: Use
/etc/nginx/conf.d/for virtual host files - Fedora/RHEL packages: Use
/etc/nginx/conf.d/
If you are unsure which layout applies to your system, you can verify the include paths by checking the main configuration:
grep -E "include.*(sites-enabled|conf\.d)" /etc/nginx/nginx.conf
Before editing any Nginx configuration, create a backup:
sudo cp /etc/nginx/sites-available/example.com /etc/nginx/sites-available/example.com.bak
Redirect Non-WWW to WWW
To redirect example.com to www.example.com, create a dedicated server block that catches requests to the non-www domain and redirects them. This approach is cleaner than using if statements inside your main server block, and it also improves readability when managing multiple sites.
HTTP Configuration
For HTTP-only sites (or as part of a larger configuration that handles HTTPS separately), add this server block:
server {
listen 80;
listen [::]:80;
server_name example.com;
return 301 http://www.example.com$request_uri;
}
server {
listen 80;
listen [::]:80;
server_name www.example.com;
root /var/www/example.com/html;
index index.html index.htm;
# Your site configuration continues here
}
In this configuration, the first server block handles all requests to example.com and issues a 301 redirect to www.example.com, preserving the original request URI path. Meanwhile, the second block serves the actual website content.
HTTPS Configuration
Modern sites should serve all traffic over HTTPS. Consequently, this configuration handles both the www/non-www redirect and the HTTP-to-HTTPS upgrade in a single setup:
# Redirect all HTTP to HTTPS
server {
listen 80;
listen [::]:80;
server_name example.com www.example.com;
return 301 https://www.example.com$request_uri;
}
# Redirect HTTPS non-www to www
server {
listen 443 ssl;
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;
return 301 https://www.example.com$request_uri;
}
# Main site configuration
server {
listen 443 ssl;
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;
root /var/www/example.com/html;
index index.html index.htm;
# Your site configuration continues here
}
This configuration uses three server blocks: the first catches all HTTP traffic and redirects to HTTPS www, the second handles HTTPS requests to the non-www domain, and the third serves your actual site content on the canonical www domain.
Redirect WWW to Non-WWW
Alternatively, if you prefer example.com as your canonical domain without the www prefix, reverse the redirect logic. This approach is increasingly popular for shorter, cleaner URLs.
HTTP Configuration
For HTTP-only setups, use a dedicated server block to redirect www traffic to the bare domain:
server {
listen 80;
listen [::]:80;
server_name www.example.com;
return 301 http://example.com$request_uri;
}
server {
listen 80;
listen [::]:80;
server_name example.com;
root /var/www/example.com/html;
index index.html index.htm;
# Your site configuration continues here
}
HTTPS Configuration
For production sites using SSL, this configuration redirects both HTTP traffic and HTTPS www traffic to the canonical non-www domain:
# Redirect all HTTP to HTTPS
server {
listen 80;
listen [::]:80;
server_name example.com www.example.com;
return 301 https://example.com$request_uri;
}
# Redirect HTTPS www to non-www
server {
listen 443 ssl;
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;
}
# Main site configuration
server {
listen 443 ssl;
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.com/html;
index index.html index.htm;
# Your site configuration continues here
}
Using Rewrite Rules (Alternative Method)
While return 301 is the recommended approach for simple redirects, you may still encounter existing configurations using the rewrite directive. Although the rewrite method works, it introduces unnecessary regular expression processing for straightforward domain redirects.
For reference, here is the rewrite equivalent for redirecting www to non-www:
server {
listen 80;
listen [::]:80;
server_name www.example.com;
rewrite ^(.*)$ http://example.com$1 permanent;
}
The ^(.*)$ pattern captures the entire request URI, and $1 appends it to the target domain. The permanent flag produces a 301 redirect. However, since no URI transformation is needed beyond changing the domain, return 301 achieves the same result more efficiently. For more complex URL manipulation scenarios, see our guide on creating rewrite rules in Nginx or the official Nginx rewrite module documentation.
Test and Apply Configuration
After adding your redirect configuration, test the syntax before applying changes. A syntax error in any Nginx configuration file can prevent the service from reloading.
Validate Configuration Syntax
First, run the Nginx configuration test:
sudo nginx -t
A successful test displays:
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful
If the test fails, however, Nginx reports the file and line number containing the error. Common issues include missing semicolons, unmatched braces, or typos in directive names.
Apply Changes
Once the syntax test passes, reload Nginx to apply the new configuration without dropping active connections:
sudo systemctl reload nginx
Verify Redirects
Next, test that redirects work correctly using curl with the -I flag to fetch only headers:
curl -I http://example.com
For a non-www to www redirect, you should see output similar to:
HTTP/1.1 301 Moved Permanently Server: nginx/1.x.x Date: Sat, 04 Jan 2026 11:00:00 GMT Content-Type: text/html Content-Length: 162 Connection: keep-alive Location: http://www.example.com/
The 301 Moved Permanently status and Location header pointing to your canonical domain confirm the redirect is working. Additionally, test both the HTTP and HTTPS versions if your configuration handles both protocols.
Troubleshooting Common Issues
Redirect Loop (ERR_TOO_MANY_REDIRECTS)
If your browser displays “too many redirects,” the configuration is creating a loop where one redirect leads to another that points back. This typically happens when:
- The same
server_nameappears in multiple server blocks with conflicting redirects - An upstream proxy or CDN is adding its own redirects
- WordPress or another CMS has site URL settings that conflict with Nginx
To diagnose this issue, check for duplicate server blocks handling the same domain:
grep -r "server_name.*example.com" /etc/nginx/
SSL Certificate Errors
When you are redirecting HTTPS traffic, both domain names must be covered by your SSL certificate. If you see certificate warnings, verify that your certificate includes both names:
openssl x509 -in /etc/letsencrypt/live/example.com/fullchain.pem -text -noout | grep -A1 "Subject Alternative Name"
The output should list both DNS:example.com and DNS:www.example.com. If one is missing, you will need to regenerate the certificate to include both domains.
Changes Not Taking Effect
If redirects do not work after reloading Nginx:
- First, confirm the configuration file is included by checking that it is symlinked in
sites-enabledor present inconf.d - Then, clear your browser cache or test with
curlto bypass cached redirects - Finally, check Nginx error logs for issues:
sudo tail -20 /var/log/nginx/error.log
Additional Resources
For more advanced Nginx configuration, these related guides may help:
- How to redirect URLs in Nginx covers path-based redirects and regex patterns
- Creating rewrite rules in Nginx explains complex URL transformations
- Configuring security headers in Nginx for production hardening
- Enabling gzip compression in Nginx to improve site performance
Conclusion
You now have a working Nginx configuration that redirects all traffic to your canonical domain format. The 301 permanent redirect ensures search engines consolidate rankings under a single URL, and the return directive handles this efficiently without regex overhead. After verifying the redirect with curl -I, your site is ready for consistent, predictable URL handling.