Adding custom redirects with custom-redirects.php

Category: Tutorials | Last modified: November 16, 2020

Although there are plugins (such as Redirection) that can help you create redirects on your site, there is a way to have more (programmatic) control over redirects on our platform: custom-redirects.php.

To implement redirects on a Pressable site without using a plugin, first you need to add the custom-redirects.php file via SFTP to your site root. For example, if your site is called “test.mystagingwebsite.com”, then this file should be located here: test.mystagingwebsite.com/custom-redirects.php.

Once you have created the file, you’ll need to add your PHP code.

Example #1: You want to redirect https://test.mystagingwebsite.com/subdir to https://test.mystagingwebsite.com/subdir-new. In this case, you could insert the following code into custom-redirects.php:

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

Example #2: You want to block traffic for specific geographies. For example, let’s imagine you wanted to block all traffic outside of the United States. This could be achieved with the following code:

<?php
if ( $_SERVER['GEOIP_COUNTRY_CODE'] !== 'US' ) {
    header('HTTP/1.1 404 Not Found', true, 404); 
    exit;
}
?>

Finally, as custom-redirects.php is called before our must-use page caching plugin (Batcache), the PHP rendered in this file is exempt from page caching by default. In other words, using $_SERVER['GEOIP_COUNTRY_CODE'] or another variable, which will vary from user-to-user, won’t be cached in custom-redirects.php, but it would be cached if used in a plugin or a theme.

An Automattic Invention A family of WordPress solutions.