Posts Tagged ‘apache’

Add tracking code to static content

By using a combination of WordPress, Piwik, and the WP-Piwik plugin, I’m able to track analytics on all the pages of my blog. However, my site is more than my blog, and I wanted to track visits to my static pages, namely my portfolio and my Post Voting app. One idea is to paste in the tracking code and just have it be versioned like my other static content. I see two downsides to this:

  1. The tracking code could change, and then I’d be updating it across all the pages, polluting the version history and causing a mess of confusion.
  2. The tracker would track my own visits that happen as I do web development on the various pages.

The solution is to use Server Side Includes to include the tracking code. This addresses the two concerns above:

  1. The tracking code is stored as a separate file, so it can be versioned independently.
  2. The include can be conditional on whether this is a development or production server.

As a further feature, I wanted the tracking code source file to be hidden from anybody that tries to access it directly. (Not really essential, but it helps me learn about configuring .htaccess)

Running into snags

I ran into two snags that helped me learn a lot more than I had originally intended. First, while trying to get the syntax of the conditional include right, I was reading the Apache documentation. However, I failed to realize that my development machine had Apache 2.2, and my web host has Apache 2.4. I was reading the documentation for Apache 2.4 ap_expr syntax. I was stumped as to why the code worked on my web host, but gave an Invalid expression error on my development machine. The solution was to create a new virtual machine using the same version of Apache as my web host. The lesson learned was to ensure that development and production environments are as close in configuration as possible.

The second snag happened when I restricted access to my tracking code piwik.html using .htaccess. I realized that this also restricted mod_include from including it! The solution came from reading the Apache 2.4 documentation for mod_rewrite. The NS flag prevents a rule from applying to an internal subrequest.

The solution

In portfolio and postvoting folders, I renamed index.html to index.shtml. The include source code which follows was added to each page:

<!--#if expr="%{SERVER_NAME} == 'bobbyratliff.nfshost.com'" -->
<!--#include virtual="piwik.html" -->
<!--#endif -->

You can view the current version of the Piwik tracking code on github.

The .htaccess file has the following line added to it:

RewriteRule ^/?piwik.html$ - [F,L,NS]

That’s all there is to it. Just use the static deploy method and your site will be updated.