Home • Blog • Article

How Can I Remove www from My WordPress Site

By Fathima Nourin TM • •

Technical Guide: Enforcing Non-WWW Domain Normalization and URL Architecture in WordPress

Problem Statement & Impact

Domain canonicalization is a critical architectural requirement for maintaining a secure, performant, and search-optimized WordPress instance. When a WordPress core application or its underlying web server responds to requests on both apex domains (https://yoursite.com) and subdomain variants (https://www.yoursite.com) without an enforced redirection policy, the hosting stack suffers from several systemic vulnerabilities and performance penalties.

From a security perspective, serving content across disparate host headers fragments session management, introduces complex Cross-Origin Resource Sharing (CORS) edge cases, and complicates TLS/SSL certificate boundary validation. If an administrator issues a wildcard SSL certificate, both variants resolve securely; however, misconfigured intermediate certificate chains or strict HSTS (HTTP Strict Transport Security) policies can trigger browser security warnings if cookies scoped strictly to the apex domain are passed over unnormalized requests.

From an infrastructural and SEO standpoint, non-canonical domain delivery causes search engine web crawlers to index duplicate content entries. This dilutes page rank authority (link equity), increases crawl budget consumption, and triggers cache fragmentation at the Content Delivery Network (CDN) and object cache layers. Reverse proxies such as Varnish, Nginx, or Cloudflare will cache duplicate copies of identical HTML payloads under different cache keys (keyed by the Host header), thereby degrading cache hit ratios and inflating origin server CPU and database query overhead.

🚨 Facing an active site error or malware warning?

Chat with an engineer on WhatsApp within 15 minutes.

💬 Chat on WhatsApp

This technical guide details the precise, step-by-step procedures required to strip the “www” prefix from a WordPress environment running on Apache or Nginx web servers, update core application states via WP-CLI, execute targeted database serialization replacements safely, and enforce robust caching and security headers.

Root Cause Analysis & Architecture

The core mechanics of WordPress domain resolution rely on two distinct configuration layers: the application layer (stored in the WordPress database table wp_options under the keys siteurl and home) and the server/network transport layer (managed by web server rewrite rules, DNS A/CNAME records, and edge proxies).

When an HTTP request enters the infrastructure stack:

  1. The Domain Name System (DNS) resolves the incoming hostname to an IP address via A or AAAA records. For a non-www migration, the www CNAME or A record must eventually point to the same origin server IP to catch legacy traffic, which is then intercepted by the web server daemon.
  2. The web server (Apache with mod_rewrite or Nginx with standard server blocks) evaluates the incoming Host header against defined server directives. Without a permanent 301 redirect rule at this layer, the request is passed directly to the PHP-FPM application pool.
  3. WordPress boots up via wp-settings.php, initializing constants derived from database parameters or wp-config.php overrides (such as WP_HOME and WP_SITEURL). If the request URL does not match these constants, WordPress may dynamically attempt redirection or, worse, generate internal links matching the unnormalized requested host header, leading to mixed-content warnings and broken asset loading.

When executing a migration from www to non-www, simply altering the database records is insufficient. Static assets, post content, serialized theme options, and widget configurations often contain hardcoded absolute URLs. Blind string replacement via standard SQL queries (e.g., standard SQL REPLACE() statements) will corrupt serialized PHP arrays because the string length indicators embedded within serialized data structures become invalid, leading to broken widgets, lost customizer settings, and PHP fatal errors in the administration dashboard.

Step-by-Step Implementation & Remediation Guide

Step 1: Update WordPress Core Constants and Database States via WP-CLI

While database options can be updated through the WordPress Administration Dashboard under Settings > General, production environments demand programmatic precision. Using WP-CLI ensures immediate state changes without risking UI lockouts.

First, access your server via SSH and navigate to the WordPress root directory. Execute the following commands to update the core options:

cd /var/www/html
wp option update siteurl 'https://yoursite.com'
wp option update home 'https://yoursite.com'

If your wp-config.php file defines hardcoded URL overrides, you must update or remove those definitions to prevent configuration drift. Open wp-config.php and ensure the following lines reflect the non-www domain:

define( 'WP_HOME', 'https://yoursite.com' );
define( 'WP_SITEURL', 'https://yoursite.com' );

Step 2: Enforce 301 Redirects at the Web Server Level

Redirecting at the web server layer prevents unnormalized requests from ever reaching the PHP execution layer, drastically reducing server resource consumption. Choose the configuration block corresponding to your web server stack.

Apache (.htaccess Configuration)

Insert the following rewrite rules directly at the top of your .htaccess file, immediately beneath RewriteEngine On:

# BEGIN Non-WWW Enforcement
RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\.(.+) [NC]
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
# END Non-WWW Enforcement

Nginx Server Block Configuration

For Nginx installations running PHP-FPM, separate server blocks should be established to catch www traffic and issue an immediate 301 Moved Permanently response:

# Catch-all server block for www variant
server {
    listen 443 ssl http2;
    server_name www.yoursite.com;

    ssl_certificate /etc/letsencrypt/live/yoursite.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/yoursite.com/privkey.pem;

    return 301 https://yoursite.com$request_uri;
}

# Primary server block for non-www apex domain
server {
    listen 443 ssl http2;
    server_name yoursite.com;

    root /var/www/html;
    index index.php index.html;

    ssl_certificate /etc/letsencrypt/live/yoursite.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/yoursite.com/privkey.pem;

    # Standard WordPress rewrite rules
    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
    }
}

Step 3: Perform Safe Database Search-and-Replace via WP-CLI

To prevent serialized data corruption, utilize WP-CLI’s built-in search-and-replace command, which correctly handles serialized PHP data structures across all database tables.

Execute a dry run first to inspect the exact number of anticipated replacements across your database tables:

wp search-replace 'https://www.yoursite.com' 'https://yoursite.com' --dry-run
wp search-replace 'http://www.yoursite.com' 'https://yoursite.com' --dry-run

Once you verify that the targeted replacement counts align with expectations, execute the live database update:

wp search-replace 'https://www.yoursite.com' 'https://yoursite.com' --all-tables
wp search-replace 'http://www.yoursite.com' 'https://yoursite.com' --all-tables

After completing the database updates, flush the WordPress object cache and transient data:

wp cache flush
wp transient delete --all

Production Hardening & Edge Cases

Executing a domain restructuring task in a production environment introduces several edge cases that require careful engineering mitigation:

  • CDN and Edge Caching Invalidation: If you utilize Cloudflare, Fastly, or an origin-pull CDN, cached edge nodes may continue serving stale 301 loops or old HTML payloads containing www assets. Perform a global cache purge immediately following the implementation of web server redirects.
  • Mixed Content and CSP Violations: Hardcoded external scripts, iframe embeds, or CSS background images referencing https://www.yoursite.com will trigger mixed-content blocks in modern browsers if the primary domain is strictly non-www. Implement a robust Content Security Policy (CSP) header and audit browser developer console network tabs post-migration.
  • Cookie Scoping and Authentication Drops: Users currently authenticated via auth cookies scoped specifically to .www.yoursite.com may experience session termination. Ensure authentication cookies are scoped to the apex domain by defining proper cookie constants if custom plugins handle session persistence.
  • DNS Propagation Delays: Ensure that TTL (Time To Live) values for your DNS records were lowered prior to making structural routing changes, ensuring rapid propagation of updated CNAME or A records across global recursive resolvers.

Diagnostic Verification & Checklist

Post-implementation validation must be conducted systematically to confirm that all redirection pathways, SSL handshakes, and database integrity metrics function correctly.

Verification Step Expected Result / Target Metric Diagnostic Command / Tool
HTTP WWW Request Header HTTP/1.1 301 Moved Permanently pointing to non-www curl -I https://www.yoursite.com
SSL Certificate Validity Valid SAN (Subject Alternative Name) covering apex domain openssl s_client -connect yoursite.com:443 -servername yoursite.com
Database Serialization Check Zero instances of remaining www.yoursite.com strings wp search-replace 'www.yoursite.com' 'yoursite.com' --dry-run
Object Cache Status Flushed state, zero stale object references wp cache flush
Search Engine Indexing Updated property verified, XML sitemap submitted Google Search Console URL Inspection Tool

Monitor your web server error logs and PHP application logs for any anomalous 404 errors, database serialization notices, or redirect loops:

tail -f /var/log/nginx/yoursite.com.error.log
tail -f /var/log/apache2/error.log

By enforcing strict web server redirection rules, updating core application states programmatically via CLI, and executing serialized database string replacements, administrators ensure a secure, high-performance, and SEO-compliant WordPress infrastructure.

Follow SiteSuraksha on Google
Add us to your preferred sources for verified WordPress & hosting guides.
FREE 30-SECOND DIAGNOSTIC

Is Your Website Fast & Secure?

Run an instant scan for security vulnerabilities, bloated plugins, and TTFB latency.

🔍 Test Your Site Now →
Map Your Issue to Guaranteed IT Care
Security & Malware
Hacks, 0-day exploits & backup failures
Pro Care (₹5,420/mo) →
Speed & Cloud Bills
Slow checkout, high TTFB & cloud waste
Pro Care (₹5,420/mo) →
ERP & Automation
GST pipelines, RPA & AI support agents
Enterprise (₹14,999/mo) →
EXPERT WORDPRESS CARE

Need Help Securing or Speeding Up Your Site?

Get 24/7 proactive security WAF, daily cloud backups, and sub-second speed optimization from ₹3,470/mo.

💬 Chat on WhatsApp Explore Plans
← Back to All Articles