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 the Managed WordPress platform: custom-redirects.php.
To implement redirects on a Managed WordPress site without using a plugin, first you need to create/add the custom-redirects.php file via SFTP to your site root. For example, if your site is called “testingsite”, then this file should be located here: /testingsite/custom-redirects.php
.
Once you have created the file, you’ll need to add your PHP code.
Note: Don’t forget to add opening and closing PHP tags as needed around your 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:
if ( $_SERVER['REQUEST_URI'] == '/subdir' ) {
header('HTTP/1.1 301 Moved Permanently');
header('Location: /subdir-new');
exit;
}
Example #2: You want to redirect a root domain or sub-domain for ex https://your-domain.site.com to an external URL https://externeral-url.com/news. In this case, you could insert the following code into custom-redirects.php:
if ( $_SERVER['HTTP_HOST'] == 'https://your-domain.site.com' &&
$_SERVER['REQUEST_URI'] == '/' ) {
header('HTTP/1.1 301 Moved Permanently');
header('Location: https://externeral-url.com/news');
exit;
}
Example #3: 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:
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.
Comments
0 comments
Article is closed for comments.