Home • Blog • Article

How to Change the URL of Your WordPress Site

By Fathima Nourin TM • •
, ,

Problem Statement & Impact

Modifying a WordPress site URL—whether transitioning from HTTP to HTTPS, migrating to a new domain name, or moving a staging environment to production—is a core administrative operation that carries significant security and operational risks. The WordPress application architecture relies heavily on absolute URLs stored serialized within database rows, configuration files, and theme templates. When a URL change is executed incorrectly or incompletely, it frequently triggers cascading failures across the application stack.

The primary technical challenges stem from how WordPress handles data storage. The core application, plugins, and themes store internal links, image attachments, stylesheet references, and JavaScript paths as absolute strings within the MySQL/MariaDB database. Specifically, tables such as wp_posts, wp_postmeta, wp_options, and custom post type tables contain serialized PHP arrays where string lengths are explicitly defined. A naive string replacement using basic SQL queries (such as UPDATE wp_posts SET post_content = REPLACE(...)) will corrupt these serialized arrays, leading to broken plugins, blank administrative screens, or complete application failure due to PHP unserialization errors.

From a security perspective, improper URL migration severely impacts cryptographic and transport layer integrity. If an administrator shifts from HTTP to HTTPS without updating all internal references, the browser encounters Mixed Content vulnerabilities, blocking critical scripts and stylesheets. Conversely, if security headers such as HTTP Strict Transport Security (HSTS) are active on the origin server while the WordPress application core still serves internal asset references over unencrypted HTTP, persistent redirect loops (ERR_TOO_MANY_REDIRECTS) occur. These disruptions degrade user trust, compromise SEO equity, and introduce attack vectors via unencrypted fallback traffic.

🚨 Facing an active site error or malware warning?

Chat with an engineer on WhatsApp within 15 minutes.

💬 Chat on WhatsApp

Root Cause Analysis & Architecture

To execute a secure and clean URL modification, administrators must understand the HTTP request lifecycle and the specific database tables governing WordPress routing. When a browser initiates a request, Nginx or Apache hands the execution to PHP-FPM via FastCGI. WordPress initializes through wp-settings.php, querying the database for siteurl and home parameters stored in the wp_options table.

  • Site Address (WP_SITEURL): The absolute URL where core WordPress files (such as wp-admin and wp-includes) reside.
  • WordPress Address (WP_HOME): The public-facing URL visitors type into their browsers to access the root of the website.

If these two parameters diverge from the actual routing configuration or fail to match the SSL certificate common name (CN) or Subject Alternative Name (SAN), TLS handshakes may fail or reverse proxies (such as Cloudflare or Varnish) will loop requests indefinitely. Furthermore, WordPress configuration constants defined in wp-config.php override database values:

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

When these constants are explicitly declared in wp-config.php, the corresponding rows in the wp_options table are dynamically bypassed during runtime, though many plugins still query the database directly. Therefore, a complete remediation strategy requires synchronizing the wp-config.php constants, updating the wp_options table records, and performing a safe, serialization-aware search-and-replace across all content tables.

Step-by-Step Implementation & Remediation Guide

Step 1: Establishing a Comprehensive Backup

Before executing database alterations or file modifications, generate a full system backup containing both the filesystem and the MySQL database. Using WP-CLI, execute the following commands:

# Navigate to the WordPress root directory
cd /var/www/html

# Export the database with table prefix integrity
wp db export pre-migration-backup.sql --allow-root

# Create a compressed archive of the web root
tar -czf wp-filesystem-backup.tar.gz .

Store these archives in an isolated off-site storage location before proceeding with structural alterations.

Step 2: Hardcoding Core Constants in wp-config.php

To enforce the new URL at the application initialization layer and prevent administrative overrides from the dashboard, declare the home and site URLs directly inside wp-config.php. Insert these lines above the /* That's all, stop editing! */ comment block:

define('WP_HOME', 'https://new-domain.com');
define('WP_SITEURL', 'https://new-domain.com');

This ensures that regardless of transient database corruption, the application core attempts to resolve assets and administrative endpoints using the designated secure URI.

Step 3: Performing Serialization-Safe Database Search-and-Replace

Standard SQL `REPLACE()` functions destroy PHP serialized data because they alter string lengths without updating the enclosing array metadata. Use WP-CLI to perform a safe search-and-replace that handles serialized strings natively:

# Perform a dry run to inspect affected tables and rows
wp search-replace 'http://old-domain.com' 'https://new-domain.com' --dry-run --allow-root

# Execute the live search and replace across the entire database
wp search-replace 'http://old-domain.com' 'https://new-domain.com' --all-tables --allow-root

If WP-CLI is unavailable, execute a secure PHP script utilizing a serialization-aware replacement library (such as Sebastian Bergmann’s recursion-safe serializer parser) rather than raw SQL statements.

Step 4: Flushing Application Caches and Permalinks

Cached object states and rewrite rules will continue serving stale routing endpoints until explicitly cleared. Purge object caches and regenerate rewrite rules using the command line:

# Flush the WordPress object cache
wp cache flush --allow-root

# Regenerate URL rewrite structures
wp rewrite flush --hard --allow-root

Production Hardening & Edge Cases

Real-world WordPress deployments often utilize reverse proxies, load balancers, or SSL termination modules that complicate URL transitions. When migrating a site behind a Cloudflare or AWS CloudFront edge layer, ensure that Flexible SSL modes are avoided in favor of Full (Strict) mode. If the origin server communicates over HTTP while the edge terminates HTTPS, WordPress will enter an infinite redirect loop unless the SSL termination headers are explicitly parsed by the application.

To resolve this, add the following dynamic detection block to the top of wp-config.php (immediately below the opening <?php tag):

if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {
    $_SERVER['HTTPS'] = 'on';
}

Performance trade-offs must also be managed. Utilizing object caching mechanisms such as Redis or Memcached means stale URL structures can persist in memory even after database updates. Always restart the Redis or Memcached service immediately following a database migration:

sudo systemctl restart redis-server

File permission configurations must be validated to prevent unauthorized write access to wp-config.php after hardcoding the URL parameters:

sudo chown -R www-data:www-data /var/www/html
sudo find /var/www/html -type d -exec chmod 755 {} \;
sudo find /var/www/html -type f -exec chmod 644 {} \;
sudo chmod 400 /var/www/html/wp-config.php

Diagnostic Verification & Checklist

Post-implementation validation requires systematic verification of HTTP response codes, asset loading integrity, and database integrity metrics. Use the following verification matrix to confirm the migration was successful:

Verification Item Expected State Diagnostic Command / Method
HTTP Response Header HTTP/2 200 OK (No redirect loops) curl -I -L https://new-domain.com
Mixed Content Audit Zero HTTP asset requests in console Browser Developer Tools (Network Tab / Security Tab)
WP-CLI DB Check No residual old domain strings remaining wp search-replace 'old-domain.com' 'new-domain.com' --dry-run
Admin Panel Access Reachable without authentication dropouts Navigate to https://new-domain.com/wp-login.php
SSL Certificate Chain Valid issuer, matching SAN/CN openssl s_client -connect new-domain.com:443 -servername new-domain.com

Monitor system logs continuously during the transition window to catch early anomalies:

# Monitor Nginx error logs for upstream proxy failures
sudo tail -f /var/log/nginx/error.log

# Monitor PHP-FPM execution errors
sudo tail -f /var/log/php8.2-fpm.log

Professional WordPress Support & Care

Maintaining a high-performing, secure WordPress site requires continuous monitoring and proactive updates. At SiteSuraksha, our dedicated technical team provides 24/7 security hardening, speed optimization, and hands-on maintenance so you can focus on growing your business.

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