Adding style and Google Analytics to an Apache directory index (mod_autoindex)

I recently had to spruce up a password-protected Apache directory index site that is being used to host some files for download.

In addition to making it look more presentable, I also discovered that you can inject code into the <head> of the index page. This allowed me to achieve what I’d wanted to do for a while on that site – track visitors using Google Analytics.

To do so you already need to be using indexes and FancyIndexing. Then, simply add the following to your .htaccess file:

IndexHeadInsert "var _gaq = _gaq || [];_gaq.push(['_setAccount', '{INSERT TRACKING CODE HERE}']);_gaq.push(['_trackPageview']);(function() {var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);})();"

Here’s the rest of my .htaccess file, excluding the security section:

Options +Indexes

IndexOptions +FancyIndexing
IndexOptions +FoldersFirst
IndexOptions +XHTML
IndexOptions +HTMLTable
IndexOptions +SuppressRules
IndexOptions +NameWidth=*
IndexOptions +SuppressDescription

IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t /resources /cgi-bin

IndexStyleSheet "/resources/style.css"

IndexHeadInsert "var _gaq = _gaq || [];_gaq.push(['_setAccount', '{INSERT TRACKING CODE HERE}']);_gaq.push(['_trackPageview']);(function() {var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);})();"

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s