Script to Verify a Page's Host Domain

This short script goes in your page's header to verify that the domain matches the expected host. If it doesn't match, you can redirect the user to another URL.

Posted by David Coleman on May 9, 2018

NB: Use this at your own risk. You can create a mess if you screw up, including making your website's public pages inaccessible.

Here's a quick little snippet that can be used in a page's HTML header to check the domain that the page is current published on and, if it doesn't match, to redirect the user to a different URL. It can be handy when your pages or site finds itself, shall we say, "misplaced" on another domain.

<script type="text/javascript">
if (window.location.hostname !== "YOURDOMAIN.com") {
window.location.replace("https://REDIRECTURL"); }
</script>

The logic is very simple: when the page is loaded in the browser, the script checks the page's host domain. If that doesn't equal the value you've set, then it redirects the user to a target URL.

Change the YOURDOMAIN.com part to the legitimate, original domain that the page should be on. Be precise, even with things like http and https, because the script is not going to forgive typos. And if you get it wrong, you can end up making your public pages inaccessible even to you.

Change the REDIRECTURL part to the target URL you want the user redirected to in case there's a mismatch. You might want to send them to the legitimate URL, but you can technically put anything you like in there.

Put the script before the closing tag. If you're using a CMS like Wordpress, there are plugins that can make it easy to insert script into the header of every page. Some themes also have that functionality.

If you open the page on your legitimate host domain, you shouldn't see anything happen at all. The host domain should match the expected domain, in which case nothing happens. To test whether it's working, you really need to upload the page to a different domain. Another option is to include a deliberate mistake in the YOURDOMAIN.com field, but that's note ideal for a live site if you're deploying site-wide.

This doesn't prevent piracy or web scraping by any stretch of the imagination, and it's very easy to overcome if the "borrower" knows what they're doing, but if the web scraper is on autopilot--as many of them are--it might just buy you a little time and open up some other remedies as you work through the laborious process of getting your "borrowed" content taken down.