Creating "vanity" URLs
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:
- To redirect a user to File B when they try to access File A
- Restrict/allow access to particular directories or files (with a little help from .htpasswd)
- To beautify long, cryptic URLs
The way in which .htaccess accomplishes #3 is via modrewrite. Here us some more information regarding this Apache module. To enable modrewrite, 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.
Written by Zak Dziczkowski
Related protips
4 Responses
Why does the regex end with "[^.php]"? It avoids strings ending any of the four characters? Do you mean to avoid matching ".php" suffix?
@hupili Great question. The point is to match urls like http://example.com/zak but not match urls like http://example.com/contact.php in case a PHP script was being access directly. My little article is about vanity urls for user profiles. If I wanted to clean up ALL of my urls, I would add another rule. :)
hello there, am trying to use this vanity url just like twitter/myusername so my index page that is index.php takes care of pulling the user profile help me out. please
here is the code am using code am using its working but not as a vanity url
it redirects users to http://www.thebusinessdrive.com/index.php/baxtelogs instead of
http://www.thebusinessdrive.com/baxtelogs
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (.*) http://www.thebusinessdrive.com/index.php/$1 [NC]
please help me out with this issue