Javascript Frame Busting or Proper Apache Headers

I’m a fan of David Walsh; whom recently posted a snippet of JavaScript to block an iFrame.

1
2
3
if (top.location != self.location) {
top.location = self.location.href;
}

[caption align=”aligncenter”]View this on gist.github.com[/caption]

But you can and should invest in a better solution. As one of the solutions pointed out on Stack-Overflow shows you can add the SameOrigin header at the server level. It works and works well. You can even allow certain pages over others.
A quick Apache solution looks like this:


  # ...
  
   # Allow some urls, block all others; whitelisting
   
    # Block any site from applying an iframe.
    Header always append X-Frame-Options SAMEORIGIN 
   
  

This technique works in all browsers and is something you can’t just turn off by disabling JavaScript (ie. It’s more secure).

Also note the Apache parameters for the the whitelisting. If you want to block your entire site from iFrames, then you do not need the LocationMatch. Otherwise, any strings that you put in the regex, if found in the url, will not block iFrames. This is useful if you do not want to block a page thats purpose is to be in a frame (like a bookmarklet script).