Prevent JavaScript Hotlinking with .htaccess

By  on  

Almost a decade (!) ago I wrote a post about preventing image hotlinking.  We all have the right to protect imagery hosted on our domain because it can slow our site down tremendously.  I love that post because it shows you how to replace the image requested with any image of your choosing; for example, I could replace any incoming image request with my logo:

<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteCond %{HTTP_REFERER} !^$
  RewriteCond %{HTTP_REFERER} !^https://davidwalsh.name/.*$ [NC]
  RewriteRule .*.(png|gif|jpe?g)$ [F,NC]
</IfModule>

But what should we do when someone is hotlinking JavaScript files?  I've written a ton about JavaScript over the years, oftentimes providing a demo page, so you can probably guess I host many JavaScript files, including all of my MooTools plugin files.  I've chosen a somewhat harsh approach to prevent hotlinking of JavaScript files:

<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteCond %{HTTP_REFERER} !^$
  RewriteCond %{HTTP_REFERER} !^https://davidwalsh.name/.*$ [NC]
  RewriteRule \.(js)$ http://davidwalsh.name/hotlink.js [R,L]
</IfModule>

The snippet above, placed in my .htaccess file, directs my server to ignore the JavaScript file the foreign domain has requested and instead provide a hotlink.js file whose contents are a bit devious:

window.location = 'https://davidwalsh.name/';

A bit harsh?  Perhaps, but my server is put under undue stress, they shouldn't be hotlinking files, and being redirected to my site is a good indication of where they should be looking to fix the issue.  I could do worse, like serve evil.js or redirect them to an adult site, but I'd prefer not to go that far.

Protect your server from hotlinking -- you have every right to and, in the end, you're probably doing them a favor.

Recent Features

Incredible Demos

  • By
    Creating the Treehouse Frog Animation

    Before we start, I want to say thank you to David for giving me this awesome opportunity to share this experience with you guys and say that I'm really flattered. I think that CSS animations are really great. When I first learned how CSS...

  • By
    MooTools &#038; Printing &#8211; Creating a Links Table of Contents

    One detail we sometimes forget when considering print for websites is that the user cannot see the URLs of links when the page prints. While showing link URLs isn't always important, some websites could greatly benefit from doing so. This tutorial will show you...

Discussion

    Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!