Adding Custom Redirects with custom-redirects.php

Edited

Overview

While there are several plugins (like Redirection) that make redirect management easy, sometimes you need more control, especially when dealing with conditions like geographic location or early redirects before WordPress loads.

That’s where custom-redirects.php comes in.

This file allows you to create advanced, programmatic redirects on your site, without relying on a plugin, and runs before page caching is applied, giving you unmatched flexibility.


How it Works

The custom-redirects.php file lives in the web root (htdocs) of your site and is executed before the must-use caching plugin (Batcache). This means:

  • PHP in this file is not cached, even if Batcache is active.

  • You can use request-specific server variables like $_SERVER['GEOIP_COUNTRY_CODE'], $_SERVER['REQUEST_URI'], or $_SERVER['HTTP_HOST'].

  • Redirects in this file apply before WordPress loads, which makes it ideal for routing and access control.


Step-by-Step: Setting Up custom-redirects.php

  1. Connect to your site via SFTP or SSH.

    • Navigate to the site’s htdocs directory (web root).

  2. Create a new file called custom-redirects.php.

    • If it already exists, you can append to it.

  3. Open the file and insert your PHP code.

    • Make sure the file starts with the PHP opening tag: <?php


Example Use Cases

Page Redirect:

Redirect /subdir to /subdir-new:

if ($_SERVER['REQUEST_URI'] == '/subdir') {
    header('HTTP/1.1 301 Moved Permanently');
    header('Location: /subdir-new');
    exit;
}

Full Site Redirect:

Redirect a specific subdomain to an external URL:

if ($_SERVER['HTTP_HOST'] == 'your-domain.site.com' && 
    $_SERVER['REQUEST_URI'] == '/') {
    header('HTTP/1.1 301 Moved Permanently');
    header('Location: https://externeral-url.com/news');
    exit;

Geographic Blocking:

Allow access only from the US and Canada (plus CLI/FPM):

$allowedCountries = ['US', 'CA'];
$api = php_sapi_name();

if ($api == 'cli') {
    return;
}

$countryCode = $_SERVER['GEOIP_COUNTRY_CODE'] ?? 'Unknown';

if (!in_array($countryCode, $allowedCountries)) {
    header('HTTP/1.1 404 Not Found', true, 404);
    exit;
}

Pro Tip

Because custom-redirects.php Runs before caching, it's perfect for logic that varies per visitor, such as country-based routing, device detection, or custom A/B testing redirects.

If you’re using this method alongside plugins or themes with their own redirection logic, remember: this file executes first. That gives you the chance to override or short-circuit other behavior early on.