Getting www vs. non-www redirection right

Have you ever wondered if your website should include the "www" in the URL or not? Do you wish there was an easy way to pick one format and redirect all requests there? Consistency in your domain structure is incredibly vital – but often overlooked – when optimizing site performance.

In this comprehensive guide, we’ll walk through the importance of settling on either www or non-www URLs, and the various methods available to permanently redirect traffic to your preferred domain version. Whether you’re a total beginner or experienced web admin, you’ll find the exact techniques and examples needed to implement seamless www/non-www redirection.

Why www vs. non-www consistency matters

Before jumping into the how-to, it’s crucial we level-set on why having a consistent domain format matters in the first place.

According to Google themselves, websites should choose either www or non-www URLs and stick with that canonical version for all site pages. The reason comes down to site authority consolidation and preventing duplicate content penalties.

You see, Google treats www and non-www URLs as separate websites in terms of crawling, indexing, and ranking authority. For example, if some of your site links point visitors to https://www.example.com/page1 and others to https://example.com/page1, search engines see those as two different pages belonging to unique domains.

This duplication splits your website‘s authority between www and non-www versions in Google‘s eyes. It also means search spiders will index duplicate copies of all your content under alternate URLs – a big no-no.

Consolidating site equity under one canonical URL prevents dilution and duplicate content issues. Redirecting all requests to that single www or non-www version keeps things simple. Just pick one format and stick with it across all pages!

But how exactly do you implement those all-important redirects? Let‘s go over different methods based on your hosting environment and server technology:

1. Apache .htaccess rewrite rules

For websites hosted on Apache servers, the most common approach is adding rewrite conditions to the .htaccess file in your root directory:

# Redirect non-www to www
RewriteEngine on 
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]
# Redirect www to non-www
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L] 

Let‘s break this down step-by-step:

  1. RewriteEngine On enables Apache‘s rewrite module
  2. RewriteCond sets a pattern match condition
  3. !^www\. means "does NOT start with www"
  4. ^www\.(.+)$ matches/captures any host with www
  5. RewriteRule redirects requests
  6. %1 inserts captured domain without www
  7. [R=301, L] sets 301 permanent redirect and stops processing more rules

Once you add these directives to a .htaccess file in your site‘s root, all requests will get redirected to the canonical www or non-www address you specify.

Pros

  • Works for any Apache configuration including shared hosting
  • Fine-tune redirects per site section via local .htaccess
  • Lightweight method without changing global configs

Cons

  • Potential rewrite conflicts with other .htaccess rules
  • Adds processing overhead for every request

Before editing .htaccess files, always good practice to backup the file and test changes on a staging environment first.

Handling .htaccess rewrite conflicts

If adding new .htaccess directives leads to 500 errors or weird redirects, you likely have a conflict with existing rules. Some troubleshooting tips:

  • Temporarily comment out all other .htaccess code, test just the redirects, then uncomment module by module.
  • Scan the rules for duplicate instances of RewriteEngine that could cause clashes.
  • Try adding RewriteOptions InheritBefore to make the new redirects override previous ones.

Finding the exact point of failure takes trial and error, but goes quicker with a binary search approach. And when in doubt, start fresh with a clean .htaccess containing just your redirect logic!

2. Apache httpd.conf global configuration

For self-managed virtual private servers (VPS) or dedicated Apache instances, adding rewrite directives in the main httpd.conf file improves performance by avoiding .htaccess overhead:

 <Directory "/var/www/html"> 
    RewriteEngine On
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]
 </Directory>

As before, update whether you want to redirect to/from www versions:

  • !^www\. = non-www → www
  • ^www\. = www → non-www

Pros

  • Central config avoids .htaccess processing time
  • Set global redirects apply to all websites
  • Necessary for performance optimization anyway

Cons

  • Requires server shell access
  • Can‘t set custom redirects per site section

Edits to the main httpd.conf mandate a graceful restart of Apache for changes to take effect. Be cautious when modifying any global configuration files on production servers!

3. Nginx server blocks

For the Nginx users out there, redirection can be implemented right in your server block configs:

server {
  listen 80;
  listen [::]:80;

  server_name example.com www.example.com;

  return 301 $scheme://www.example.com$request_uri;  
}

server {
  listen 80;
  listen [::]:80;

  server_name www.example.com;

  # Regular site config here 
}

Here‘s what‘s happening:

  • First block catches non-www requests
  • return 301 permanently redirects
  • $scheme inserts http/https protocol
  • $request_uri appends original URI
  • Second block serves www traffic normally

As before, flip instances of www/non-www in each block to reverse. Add this code to nginx.conf and reload Nginx.

Pros

  • Clean way to implement redirects in Nginx
  • Consistent www or non-www across all sites

Cons

  • Requires command line access
  • Can‘t customize per site section

Be cautious when editing the main Nginx config. Test changes on a staging server before deploying to production to avoid downtime.

4. Cloudflare Page Rules

For sites using Cloudflare services, their Page Rules system allows implementing both simple and extremely complex redirects through an easy web UI:

  1. Browse to your domain and open the Cloudflare dashboard
  2. Visit Page Rules and create a new rule
  3. Select settings like:
    • Applies to: URL patterns for matching
    • Status code: 301 permanent redirect
    • URL to forward to: Target destination

For a basic www → non-www redirect, settings would be:

  • Applies to: http://www.example.com/*
  • Forward to: https://example.com/$2

Save changes and Cloudflare will instantly deploy your redirect everywhere without needing IT help!

Pros

  • Simple UI to manage redirects in Cloudflare
  • Very customizable matching conditions
  • Instant global deployment

Cons

  • Requires Cloudflare subscription plan
  • Passing traffic through external proxy

With Cloudflare Page Rules, you can seamlessly redirect multiple site versions like production, staging, old domain names, etc. Very convenient albeit slightly slower.

Validating redirects work properly

Once you pick a redirect method and activate it through server configs or Cloudflare, verifying everything worked is crucial before sending live traffic. Here are some tips for testing new redirects:

  • Use online crawling tools like the MOZ Redirect Chain that show stepping through URLs
  • Inspect server / CDN logs for 301 status codes
  • Check site in multiple browsers and confirm pages land correctly
  • Trigger redirects locally adjusting Host: headers to simulate non-www

Ideally both visual checks and raw logs will confirm:

  • Old URLs issue 301 Moved Permanently
  • New URLs serve 200 OK status codes
  • No redirect loops created!

Finding issues at this stage is much easier than after launch. Be extremely thorough validating both www and non-www URLs across site sections land correctly before sharing links widely.

Troubleshooting common redirect problems

Sometimes despite the best laid plans, redirects don‘t behave as expected once applied:

  • Redirect chains / loops – where URL gets stuck bouncing between non-www and www versions indefinitely. Use [R=301,L] to prevent daisy chaining.
  • Wrong landing pages – site sections redirect incorrectly. Carefully check conditional rules aren‘t too broad.
  • Incomplete URLs – redirected links forgetting https:// or index.html endings. Use absolute targeting including protocols and file paths.
  • CORS errors – redirects working but blocked by security policy errors. May need to adjust CORS headers between old and new domain formats depending on how resources are accessed.

Chasing down the actual redirect failure point requires meticulous debugging:

  • Watch requests in browser DevTools Network tab
  • Tail server access logs during test runs
  • Temporarily change redirects to 302s while testing to avoid cashing
  • Comment out sections of rules to isolate problems

Patience and incrementally narrowing down where things go awry lets you pinpoint and fix redirect bugs. Don‘t rush launching redirects until fully working both visually and under the hood!

Special considerations for WordPress sites

As one of the most popular content management systems (CMS) around, WordPress deserves special mention for configuring non-www to www or vice versa redirects:

1. Server-level rules.htaccess, httpd.conf, Nginx configs all work great for standard WordPress installations. Follow similar patterns shown for conditions and redirects based on your hosting environment.

2. WordPress redirection plugins – Extensions like Redirection and Safe Redirect Manager give user-friendly ways to manage redirects right inside the WP dashboard without touching server configs. These integrate nicely with WordPress themes and hooks to keep redirects managed in one place.

The only gotcha with WordPress is avoiding conflicts between plug-in redirection logic and existing server rewrite rules. Some trial and error may be needed to get configurations smoothly coexisting.

Start with server-level redirects when possible for performance, adding plugins mainly for fine-grained UI control over specific WordPress-related URLs.

Conclusion

Consistent domain names are vital for consolidated site performance. By redirecting www to non-www or vice versa, you avoid splitting authority across formats and duplicate content issues.

We covered server-based Apache and Nginx redirects using .htaccess, httpd.conf, and Nginx block configuration files. For sites utilizing Cloudflare CDN or WordPress CMS, their specialized tools also help manage redirects.

No matter your exact hosting environment:

  • Pick either www or non-www canonically
  • Set up 301 permanent redirects
  • Thoroughly test both old and new URLs
  • Solve problems incrementally before go-live

Once launched, periodic checks that redirection continues functioning are wise. Monitor rankings and crawler behavior reports to confirm your sole domain format enjoys consolidated authority!

Have questions on the best redirect strategies for your particular site? Don‘t hesitate to ask in the comments!