using wp_redirect to redirect wordpress pages

using wp_redirect to redirect wordpress pages

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Handling Protocol and Subdomain Variants in WordPress Redirects

Using wp_redirect() directly inside page content or a theme file is often insufficient when you need to enforce specific redirect rules regardless of HTTP/HTTPS or www vs non-www. The core issue lies in how the URL string is constructed. If your source URL contains user input like $_SERVER['REQUEST_URI'], it will preserve whatever scheme or host the browser sent. To force a canonical destination, you must explicitly construct the target URL without inheriting the incoming request's context.

In the example provided, placing the redirect logic inside the page content creates a race condition. If an external link points to http://example.com/contact-us-3/, and that page contains code attempting to redirect to https://www.example.com/contact-us/, the browser might fail to load the script if the initial request is unencrypted (HTTP). The server must validate the incoming request and decide on the redirect before the browser even parses the HTML. Therefore, you should not rely on output buffering or page content; instead, implement this logic in functions.php within a child theme.

This approach ensures the redirect hook fires globally for any matching URL pattern, independent of what is displayed on the page. You do not need to create a dummy "contact-us-3" page just to house the code. Instead, define a custom function that checks the incoming request URI and performs the redirect if it matches the slug you want to migrate.

The implementation requires careful handling of the URL components. wp_redirect() expects a fully qualified domain name (FQDN). If your source URL is constructed dynamically, you must strip the protocol and host from the input and replace them with your canonical values. For instance, if the input is http://example.com/contact-us-3/, constructing the destination requires forcing the scheme to HTTPS and the host to include www.

Here is a practical implementation pattern for functions.php:

function enforce_canonical_redirect() {
    // Define your canonical URL components.
    // This ensures all traffic goes through https://www.example.com/contact-us/
    $canonical_scheme = 'https';
    $canonical_host   = 'www.example.com';
    
    // Construct the full canonical path.
    $canonical_url = trailingslashit($canonical_scheme . '://' . $canonical_host) . '/contact-us/';

    // Check if the current request matches the old slug.
    // Using parse_url to isolate the path allows for partial matching without regex overhead.
    $current_path = untrailingslashit(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));

    if ($current_path === '/contact-us-3/') {
        // Use wp_redirect with a 301 status code for SEO-friendly permanent redirects.
        // Note: wp_redirect() expects the full URL, so we reconstruct it here explicitly.
        wp_redirect( $canonical_url, 301 );
        exit;
    }
}

// Hook this into the 'template_redirect' action.
// This is earlier than 'init' but later than parsing the request headers.
add_action('template_redirect', 'enforce_canonical_redirect');

This method decouples the redirect logic from the page content. It runs on every request, checking if the current path matches the legacy slug. If it does, it immediately halts rendering and sends a 301 response header to the client with the new canonical URL. This handles mixed content issues automatically because the output is never sent; only headers are modified.

A common pitfall with wp_redirect() is failing to call exit immediately after the redirect. Without exiting, PHP continues executing the rest of the script, potentially flushing buffers or rendering HTML that the browser will ignore anyway but which can cause performance issues or unexpected behavior in server-side logic. Always terminate execution after calling wp_redirect().

While plugins exist for this exact use case—such as Redirection or Yoast SEO Redirects—using native WordPress functions provides tighter control over the HTTP headers and avoids loading unnecessary dependencies if your site is lightweight. However, be aware that manually managing these rules in code requires maintenance whenever you change slugs. For dynamic e-commerce sites with thousands of products, a database-driven approach might be more sustainable than hardcoding paths.

If you are migrating away from this pattern to a more scalable solution, consider tools designed for mass URL mapping. But for a specific slug migration like /contact-us-3/ to /contact-us/, the template_redirect hook remains a robust, low-overhead solution that respects your canonicalization rules without relying on external plugins.

Our network