Sunday, June 13, 2010

Creating Vanity URLs with .htaccess

I had to do this for a project website I was working on recently. We knew we wanted the user's profile to be accesible by entering the www.url.com/username. This was, more or less, created automatically when the user created a profile. I brainstormed dozens of ideas, all of which were either not secure or overly complicated. Finally, the answer came to me: .htaccess and regular expressions.

Our server is Linux-based and runs Apache for the web server. Because we use Apache, we can use .htaccess...and it is a beautiful thing.

An .htaccess file is used for a number of reasons:

1. To redirect a user to File B when they try to access File A
2. Restrict/allow access to particular directories or files (with a little help from .htpasswd)
3. To beautify long, cryptic URLs

The way in which .htaccess accomplishes #3 is via mod_rewrite. Here us some more information regarding this Apache module. To enable mod_rewrite, add the following two lines to .htaccess file:


Options +FollowSymlinks
RewriteEngine on

For the sake of example, let us say that the PHP file that handles displaying a users profile is named profile.php. Furthermore, a username may be comprised of numbers, letters (upper and lower case), periods, hyphens and underscores. Adding the following rule:

RewriteRule ^([A-Za-z0-9\._\-]+)+[^\.php]$ profile.php?&uri=$0 [NC]

 to the .htaccess file will rewrite http://www.url.com/username to http://www.url.com/profile.php?uri=username. An important note about the rewrite is that http://www.url.com/username is what is still displayed in the browser's address bar. Thus, a vanity URL!

An explanation of the regular expression used in the rule is beyond the scope of this post. Read more about using regular expressions with mod_rewrite.

    No comments:

    Post a Comment