This simple PHP script can be used to perform HTTP and HTTPS redirects for your domains. I created this script as my DNS provider does not provide a URL redirection service of their own, and I didn't want to setup webspace or a virtualhost on my server just for a redirect.
To use this script, you should already have a free IPv4 address and domain. Setup these as a host on a server or VPS -- I recommend Digital Ocean (referral link).
Redirection DNS Settings
Within your DNS settings point your domain or subdomain to the server you have setup.
For subdomains, this is done by setting up a CNAME record. For apex/naked domains, it is recommended that you use an ALIAS or ANAME record type if your DNS provider supports it. Otherwise, use an A record:
- CNAME and ALIAS/ANAME records should point to
yourdomain.com
- A records should point to
123.45.67.89
To configure the redirection destination, add a TXT record for your domain:
- TXT value:
"redirect_https://www.google.com"
Note: Remember to replace these values with your own.
Example DNS zone file
This is an example zone file for www. and non-www. addresses:
CNAME:
example.com. 1800 IN CNAME 123.45.67.89
www.example.com. 1800 IN CNAME 123.45.67.89
A Records:
www.example.com. 1800 IN A 123.45.67.89
www.example.com. 1800 IN A 123.45.67.89
TXT Values:
example.com. 1800 IN TXT "redirect_https://www.google.com"
www.example.com. 1800 IN TXT "redirect_https://www.google.com"
PHP Script
<?php
/**
* Redirect URL based on DNS TXT record value. Requires A records to be pointed to the server's IP Address and a TXT record with redirection value.
* Author: Ryan Fitton (https://ryanfitton.co.uk)
* Version: 1.0.0
*
* Examples:
* example.com. 1800 IN A 123.45.67.89
* www.example.com. 1800 IN A 123.45.67.89
* example.com. 1800 IN TXT "redirect_https://www.google.com"
* www.example.com. 1800 IN TXT "redirect_https://www.google.com"
*/
//The redirect prefix
$prefix = 'redirect_';
//Find the TXT DNS records for this host
$txts = dns_get_record($_SERVER['HTTP_HOST'], DNS_TXT);
//Loop through each TXT record
foreach($txts as $txt) {
//Loop through each record entry
foreach($txt['entries'] as $txtValue) {
//If the text record includes 'redirect_'
if (strpos($txtValue, $prefix) !== false) {
//Explode the TXT value
$explode_txtValue = explode($prefix, $txtValue);
//Set the 1st key as the URL addrress and Sanitize data
$url = filter_var($explode_txtValue[1], FILTER_SANITIZE_URL);
//Check if URL is valid
if (filter_var($url, FILTER_VALIDATE_URL)) {
//Perform a temporary redirect (302)
header('Location: ' . $url, true, 302);
exit;
//If the URL is not valid
} else {
//Display message on screen
echo 'Invalid URL: ' . $url;
exit;
}
}
}
}
?>