One of the most common questions that I get from web developers is “How do I get clean URLs without all the question marks and symbols?” The solution is not as hard as you may think, it just takes a little knowledge of the apache function mod_rewrite. In this quick tip I’ll show you one way that mod_rewrite can help you with your URLs.
By default mod_rewrite may be installed but not enabled. To fix this, create a new file called .htaccess with the following line of code:
RewriteEngine On
You’ll want to save that file in your root directory (the base directory where all your files are). After you do that, we are ready to start the rewriting process.
For our example, let’s say the URL we have is http://www.domain.com/index.php?action=view&page=home
That’s a pretty long and nasty URL and search engines don’t look highly upon it either. But the good news is we can fix it by jumping back into our .htaccess file and adding the following code:
RewriteEngine On
RewriteRule ^/(.*)/(.*).html$ /index.php?action=$1&page=$2
Now, this gives us a URL of: http://www.domain.com/view/home.html. It’s more likely that the user will remember this URL and as mentioned before, search engines prefer URLs this way.
If you curious as to what the symbols in the .htaccess file mean, let me try to break it down for you a little bit:
- The caret (^) signifies the start of an URL, under the current directory. This directory is whatever directory the .htaccess file is in.
- The dollar sign ($) signifies the end of the string to be matched. You should add this in to stop your rules matching the first part of longer URLs.
There are many more possibilities and functions of mod_rewrite, but I’ll save that for another day. For now, this has been a quick tip.