Cyber Monday Sale 40% off unlimited courses & creative assets! 40% off unlimited assets! Save Now
Advertisement

# Using htaccess Files for Pretty URLS

Read Time:13 minsLanguages:

Continuing our review of htaccess files, today we'll examine how to use mod_rewrite to create pretty URLs.

### Benefits of Formatted URLs

While some claim pretty URLs help in search engine rankings, the debate here is fierce, we can all agree that pretty URLs make things easier for our users and adds a level of professionalism and polish to any web application. I could go over all the theoretical reasons for this, but I like real-world examples better. Like it or hate it we all must admit that Twitter is a wildly popular web application and part of the reason for that is most certainly how it formats URLs. I can tell anyone in the know that my Twitter username is noahhendrix, and they know my profile can easily be found at twitter.com/noahhendrix. This seemingly simple concept has vast effects in the popularity of your application.

Just to put things in perspective we can look at another popular social networking website, Facebook. Since the site launched in 2004 the profile system has grown and evolved to better tailor to users, but one glaring hole was the URL to a profile. From the time I registered with Facebook my profile was at the URL http://www.facebook.com/profile.php?id=1304880680. That is quite a mouth full, and just recently it appears Facebook has realized that and they launched Facebook vanity URLs. Now I can share my Facebook profile by telling people my Facebook username is "noahhendrix", which they know can be found by going to facebook.com/noahhendrix. While the odds are that we won't have an application as popular as Facebook, we can still borrow a few pages from their book.

### Quick Overview

A quick overview before we dive into code, in today's tutorial we will go over two slightly different methods of creating pretty URLs using HTACCESS. The difference between the methods is whether Apache or PHP is doing the heavy lifting to break the URL apart for parsing. I want to point out that mod_rewrite tutorials are almost as old as the internet itself and this is not the first. At the end I will use one of the methods to create a simple application to show how these solutions would look in a real-live website (well not 100% production quality). The service we will create is a URL shortener that can mirrors the functionality of such sites like bit.ly, TinyURL, or su.pr. So without anymore fluff let us look at the code.

### Using Apache

First, we can place all of our code in Apache .htaccess files. This could look something like this:

Let's start at the top and work our way down to better understand what is going on here. The first line sets the environment up to follow symbolic links using the Options directive. This may or may not be necessary, but some web hosts use symlinks (similar to alias in MacOSX or shortcuts is Windows) for common HTTP request errors and these are usually symlinked files, or at least this is how I understand the reasoning. Next we tell Apache we are going to use the Rewrite Engine. The next two lines are very, very important it restricts rewriting URLs only to paths that do not actually exists. This prevents the rules below from matching example.com/images/logo.png for example. The first prevents existing directories with the !-d flag and the second with !-f means ignore existing files.

The next three lines are the actual URL rewriting commands. Each line creates a rule that tries to match a regular expressions pattern against the incoming URL. Regular expressions, at least for me, are a hard set of rules to remember but I always find it helpful to use this tutorial by Nettut's own Jeffery Way and the tool he recommends. I found it easy to type in sample URLs we want to match and then try to hack together the pattern.

The first argument is the pattern, between the caret and dollar sign. We tell Apache we want URLs asking for the users directory (an artificial directory, doesn't have to actually exist) followed by a / and any length of numbers. The parenthesis create a capture group, you can use as many of these as you want, they serve as variables that we can then transplant into our rewrite. The asterisk means the user can enter whatever they want, and it won't affect the rewrite, this is primarily to handle a trailing slash so example.com/users/123 is the same as example.com/users/123/ as users would expect.

The second argument is the path we want to actually call, this unlike the first must be a real file. We tell Apache to look in the current directory for a file called profile.php and send the parameter id=$1 along with it. Remember the capture group earlier? That is where we get the variable$1, capture groups start at one. This creates a URL on the server like example.com/profile.php?id=123.

This method is great for legacy web applications that have existing URL structures that prevent us from easily rewriting the backend to understand a new URL schema because to the server the URL looks the same, but to the user it looks much nicer.

### Using PHP

This next method is great for those who don't want to distribute too much logic to Apache and feel more comfortable in PHP (or similar scripting languages). The concept here is capture any URL the server receives and push it to a PHP controller page. This comes with the added benefit of control, but greater complexity at the same time. Your HTACCESS file might look something like this:

Everything is the same as above, except the last line so we will skip to it. Instead of creating a capture group we just tell Apache to grab every URL and redirect it to index.php. What this means is we can do all of our URL handling in PHP without relying too much on stringent URL paths in HTACCESS. Here is what we might do at the top of our index.php file to parse out the URL:

The first line is not necessary unless you application doesn't live at the root directory, like my demos. I am removing the non-sense part of the URL that I don't want PHP to worry about. $_SERVER['REQUEST_URI'] is a global server variable that PHP provides and stores the request URL, it generally looks like this: As you can see it is basically everything after the domain name. Next we split up the remaining part of the virtual path and split it by the / character this allows us to grab individual variables. In my example I just printed the$params array out in the body, of course you will want to do something a little more useful.

### Serving the Short URL

So we have the URL in the database let's work on serve.php so we can actually translate the short code into a redirect.

This one is very similar to create.php we include the database information, and store the short code sent to us in a variable called \$short. Next we query the database for the URL of that short code. If we get a result we redirect to the URL, if not we print out an error like before.

As far as PHP goes that is all we need to do, but at the moment to share a short URL users must enter this, http://shrtr.me/server.php?short=SHORT_CODE not very pretty is it? Let's see if we can't incorporate some mod_rewrite code to make this nicer.

### Pretty-ify With HTACCESS

Of the two methods I wrote about at the beginning of the tutorial we will use the Apache one because this application is already created without considering any URL parsing. The code will look something like this:

Skipping to the RewriteRule we are directing any traffic that doesn't already have a real file or directory to serve.php and putting the extension in the GET variable short. Not to bad no go try it out for yourself!

### Conclusion

Today we learned a few different ways to utilize mod_rewrite in our application to make our URLs pretty. As always I will be watching over the comments if anybody has trouble, or you can contact me on twitter. Thanks for reading!

Advertisement
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.