Custom Redirects in InstaWP Live
It is possible to modify some per-site request behavior on InstaWP Live via a custom-redirects.php.
Usage
While it is primarily used for custom redirects, custom-redirects.php can modify other behavior as it is prepended to any PHP script that is accessed on a Live site.
To get started, first create a custom-redirects.php
file within a site’s htdocs
directory. Be sure to include an opening <?php so your code can be executed.
Examples
****
The following are examples code snippets that demonstrate common custom-redirects.php
uses. Multiple modifications may be used at a time, given that they do not conflict.
Basic Page Redirect
****
if ( $_SERVER['REQUEST_URI'] == '/subdir' ) {
header('HTTP/1.1 301 Moved Permanently');
header('Location: /subdir-new');
exit;
}
Add Security Headers
****
Note that, as of January 2024, strict-transport-security headers are set automatically and cannot be modified
header('X-XSS-Protection: 1; mode=block');
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: SAMEORIGIN');
header('Referrer-Policy: no-referrer-when-downgrade');
Site Redirect
****
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;
}
Geoblocking by Country Code
****
In this example, we’ll restrict access via country codes (Alpha-2, ISO 3166-1 country codes via MaxMind). Specifically, this example allows requests from the United States and Canada while also permitting requests from PHP-FPM and CLI.
This is based on https://gist.github.com/JoshuaGoode/f9efd25bb46fe0dc4fe8c9c855fe4479
// Array of allowed country codes
$allowedCountries = ['US', 'CA'];
// Get the current server API
$api = php_sapi_name();
// Bypass geo checks for non-web server APIs
if ($api == 'fpm-fcgi' || $api == 'cli') {
return; // Early exit for CLI or FPM contexts
}
// Retrieve the country code or default to blocking access
$countryCode = $_SERVER['GEOIP_COUNTRY_CODE'] ?? 'Unknown'; // Using null coalescing operator for clarity
// Block access if the country code is not allowed
if (!in_array($countryCode, $allowedCountries)) {
header('HTTP/1.1 404 Not Found', true, 404);
exit;
}
Basic Access Block
****
if ( strpos($_SERVER['REQUEST_URI'],'{file or folder name here, no curly braces}') !== false ) {
http_response_code( 410 );
exit;
}
Limiting Access by IP
****
/**
* The following blocks the sandbox URI to anyone who isn't on a COMPANY_EXAMPLE_1 or COMPANY_EXAMPLE_2 Proxies
* 123.456.789.101 is COMPANY_EXAMPLE_1's Proxy
* 987.654.321.000 is COMPANY_EXAMPLE_2's Proxy
*/
$ips = array('123.456.789.101','987.654.321.000');
if ( strpos($_SERVER['REQUEST_URI'],'/sandbox') !== false ) {
if ( !in_array($_SERVER['REMOTE_ADDR'],$ips) ) {
header('HTTP/1.0 403 Forbidden');
echo '403 Forbidden';
exit;
}
}
Updated on: 01/05/2025
Thank you!