PHP script for URL forwarding/redirects using simple DNS TXT records

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
  • A records should point to

To configure the redirection destination, add a TXT record for your domain:

  • TXT value: "redirect_"

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:


A Records: 1800 IN A 1800 IN A

TXT Values: 1800 IN TXT "redirect_" 1800 IN TXT "redirect_"

PHP Script

 * 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 (
 * Version: 1.0.0
 * Examples:
 *         1800	IN	A
 *     1800	IN	A
 *         1800    IN	TXT	"redirect_"
 *		1800	IN	TXT	"redirect_"

//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);
            //If the URL is not valid
            } else {
                //Display message on screen
                echo 'Invalid URL: ' . $url;


  • February 17th, 2020

Thankyou so much for this tutorial, this helped me in my project.
Appreciate alot!

Post a Comment