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!

Share this post:

About Pat

I'm an I.T. systems engineer by day and in my spare time I code. I've made WordPress websites and plugins, weewx extensions and static html sites using Jekyll. I'm a technologist at heart and I enjoy tinkering on many different technology projects. Here on my site you will find some of the projects I've worked on, and other random bits of knowledge that I hope help someone along the way.

mentions