Before the hashbang
What I was able to see in Google Analytics with the hashbang was not particularly helpful. All the pages where labeled as root (/), therefore making the Bounce Rate, Avg. Session Duration and the Behaviour data useless. That's about 1/3 of the data.
How to convert to pretty URLs or HTML5 mode
The example I took for this post is the
fadeit.dk
website. At the time, it was just a company site with not that many
visits. It was hosted on a typical Apache shared server (such as
GoDaddy, MediaTemple, HostGator; you name it).
Angular was the framework of choice because we didn't
need a monster-CMS to manage content. We did want some flexibility and
Angular was able to deliver it. Because we were using JSON files to
store & supply our data, we could switch to any back-end at any time
and have everything working. Now that's flexible!
The code
First thing you have to do is turn on HTML5 mode in your main Angular module's config block. That's pretty much a one liner:
angular.module('main', []).config(['$locationProvider', function($locationProvider) {
...
$locationProvider.html5Mode(true);
...
});
After doing this, you need to create a .htaccess file on the root of your shared Apache server.
RewriteEngine On
# If an existing asset or directory is requested go to it as it is
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]
# If the requested resource doesn't exist, use index.html
RewriteRule ^ /index.html
That's it!
After the hashbang
Now that .htaccess is in place, we can use Analytics at full capacity.
How does it work?
HTML5 mode is based on the HTML5 History API, which essentially allows setting a URL on the same domain with JavaScript. The
.htaccess
file makes it possible to reload a page (or go to a hashbang-less page
for that matter) without getting a 404 response from the server.
Moreover, if the HTML5 History API is not available, your Angular
application will automatically use the hashbang as a fallback.
Read more about it on this
Angular docs page.
One more thing...
The issue with this is that now Google doesn't consider this
an AJAX Single Page Application. Therefore, I was able to notice that
the indexing (which was working fine with the hashbang) is very poor
now.
So solving a problem resulted in creating a bigger problem.
There is a good part: Google itself suggests that to benefit from proper indexing, creating
HTML Snapshots is a good idea. But that's another topic.
Looking forward to seeing your pretty URLs!
Comments
Post a Comment