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
    Select Dropdowns, MooTools, and CSS Print

    I know I've harped on this over and over again but it's important to enhance pages for print. You can do some things using simple CSS but today's post features MooTools and jQuery. We'll be taking the options of a SELECT element and generating...

  • By
    Retrieve Google Analytics Visits and PageViews with PHP

    Google Analytics is an outstanding website analytics tool that gives you way more information about your website than you probably need. Better to get more than you want than not enough, right? Anyways I check my website statistics more often than I should and...

Discussion

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