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
    spellcheck Attribute

    Many useful attributes have been provided to web developers recently:  download, placeholder, autofocus, and more.  One helpful older attribute is the spellcheck attribute which allows developers to  control an elements ability to be spell checked or subject to grammar checks.  Simple enough, right?

  • By
    CSS Columns

    One major gripe that we've always had about CSS is that creating layouts seems to be more difficult than it should be. We have, of course, adapted and mastered the techniques for creating layouts, but there's no shaking the feeling that there should be a...

Discussion

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