How to Redirect Non-WWW to WWW – Complete Tutorial

This tutorial will guide you through redirecting non-www URLs to www URLs across different platforms and hosting environments.

Why Redirect non-www to www?

  • SEO Benefits: Prevents duplicate content issues
  • Brand Consistency: Maintains consistent URL structure
  • Cookie Management: Easier cookie scope management
  • Analytics: Consolidated traffic data

Redirect Types

  • 301 Redirect: Permanent redirect (SEO-friendly)
  • 302 Redirect: Temporary redirect

HTAccess Method (Apache)

Method 1: Basic Redirect

RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]

Method 2: With HTTPS Support

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]

RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]

Method 3: Combined HTTPS and WWW

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]

Complete .htaccess Example

# Enable Rewrite Engine
RewriteEngine On

# Force WWW and HTTPS
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]

# Additional security headers (optional)
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"

Nginx Configuration

Server Block Configuration

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

server {
    listen 443 ssl;
    server_name example.com;
    
    ssl_certificate /path/to/certificate.crt;
    ssl_certificate_key /path/to/private.key;
    
    return 301 https://www.example.com$request_uri;
}

server {
    listen 443 ssl;
    server_name www.example.com;
    
    # Your main website configuration here
    root /var/www/html;
    index index.php index.html index.htm;
    
    ssl_certificate /path/to/certificate.crt;
    ssl_certificate_key /path/to/private.key;
    
    # Rest of your configuration
}

Simplified Version

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

Cloudflare Setup

Method 1: Page Rules

  1. Log in to Cloudflare dashboard
  2. Go to Rules > Page Rules
  3. Create a new page rule:
    • URL Patternexample.com/*
    • SettingForwarding URL
    • Status Code301 - Permanent Redirect
    • Destination URLhttps://www.example.com/$1

Method 2: Bulk Redirects (Enterprise)

{
  "name": "Non-WWW to WWW",
  "source": "example.com",
  "target": "https://www.example.com",
  "status_code": 301
}

cPanel Redirect

Using Redirects Interface

  1. Log in to cPanel
  2. Find Domains section
  3. Click Redirects
  4. Configure:
    • Type: Permanent (301)
    • Redirect fromexample.com
    • Redirect tohttps://www.example.com
    • Wildcard Redirect: Enable if needed

PHP Redirect

Simple PHP Redirect

<?php
$host = $_SERVER['HTTP_HOST'];
$request_uri = $_SERVER['REQUEST_URI'];

if ($host === 'example.com') {
    $new_url = 'https://www.example.com' . $request_uri;
    header('HTTP/1.1 301 Moved Permanently');
    header('Location: ' . $new_url);
    exit();
}
?>

Advanced PHP Function

<?php
function redirectToWWW() {
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'];
    $request_uri = $_SERVER['REQUEST_URI'];
    
    if ($host === 'example.com') {
        $new_url = $protocol . '://www.example.com' . $request_uri;
        header('HTTP/1.1 301 Moved Permanently');
        header('Location: ' . $new_url);
        exit();
    }
}

// Call this function at the beginning of your script
redirectToWWW();
?>

JavaScript Redirect

Client-Side Redirect

// Check if current host is non-www
if (window.location.hostname === 'example.com') {
    const newUrl = 'https://www.example.com' + window.location.pathname + window.location.search;
    window.location.replace(newUrl); // Use replace instead of assign for better UX
}

Meta Tag Redirect (Not Recommended for SEO)

<!DOCTYPE html>
<html>
<head>
    <script>
        if (window.location.hostname === 'example.com') {
            window.location.href = 'https://www.example.com' + window.location.pathname;
        }
    </script>
</head>
<body>
    <!-- Your content -->
</body>
</html>

Best Practices

1. Always Use 301 Redirects

  • Search engines transfer link equity
  • Browsers cache the redirect

2. Test Your Redirects

# Using curl
curl -I http://example.com
curl -I https://example.com

# Check for proper 301 response

3. Update Canonical Tags

<link rel="canonical" href="https://www.example.com/current-page">

4. Update Sitemap and Robots.txt

  • Ensure sitemap references www URLs
  • Update robots.txt if needed

5. Monitor Search Console

  • Add both www and non-www properties
  • Set your preferred domain

6. SSL Certificate

  • Ensure certificate covers both www and non-www versions
  • Use wildcard certificates if possible

Testing Your Redirect

Online Tools

Manual Testing

# Check HTTP
curl -I http://example.com

# Check HTTPS
curl -I https://example.com

# Expected response should include:
# HTTP/1.1 301 Moved Permanently
# Location: https://www.example.com/

Browser Testing

  1. Clear browser cache
  2. Visit non-www URL
  3. Verify automatic redirect to www version
  4. Check address bar shows www version

Common Issues and Solutions

1. Redirect Loops

Problem: Infinite redirect between www and non-www
Solution: Check your conditions and ensure they’re mutually exclusive

2. Mixed Content Warnings

Solution: Ensure all redirects point to HTTPS version

3. SSL Certificate Errors

Solution: Get certificate that covers both www and non-www domains

4. Search Engine Indexing

Solution: Use 301 redirects and update Search Console preferences


Final Recommendations

  1. Server-level redirects (Apache/Nginx) are most efficient
  2. Cloudflare/CDN redirects are good for performance
  3. Avoid client-side redirects for SEO-critical pages
  4. Always test thoroughly before going live
  5. Monitor analytics for any traffic drops

Choose the method that best fits your hosting environment and technical capabilities. Server-level redirects are generally recommended for best performance and SEO results.