WordPress – Redirect based on IP or return 404

October 13, 2015 by Pat - Comments - - 2 min read

WordPressI had a situation recently where I needed to have a WordPress permalink redirect clients if they were an “authorized” IP address. Everyone else would get a 404.

An example of this would be if you had a super long URL that you wanted to keep private, but wanted an easy-to-remember URL to access it. You should be able to access it from home, but everyone else would see a 404. A quick way to remember a URL without sacrificing security.

Here’s how I did it. Add the following to functions.php for your site’s theme.

function custom_ip_redirect() {
    global $page;
    if (is_page(100)) {
        $ip = gethostbyname('your_dynamic_dns_hostname.com');
        if ( ($_SERVER['REMOTE_ADDR'] == $ip) || ($_SERVER['HTTP_X_FORWARDED_FOR'] == $ip) ) {
            // If the client requesting the page matches the ddns for home, then redirect.
            header("Location: http://google.com");
            die();
        } else {
            // Otherwise, give a 404
            global $wp_query;
            $wp_query->set_404();
            status_header(404);
        }
    }
}
add_action( 'wp', 'custom_ip_redirect' );

It breaks down to: if the page being requested is ID 100, and your client’s IP matches the dynamic DNS hostname IP in $ip, then you’ll get redirected to Google (or your super long, super secret URL). Otherwise, you’ll get your theme’s 404 page.

If you don’t have dynamic DNS setup for your house, then you can put in your home IP for $ip, instead of gethostbyname();. However, having dynamic DNS setup for your home’s IP is a good thing so that you can continue to authenticate without having to change the code everytime your ISP renews your IP.

That’s it!

Disclosure: Some of the links on this website are affiliate links. This means that, at zero cost to you, I will earn an affiliate commission if you click through the link and finalize a purchase.
Share this post: