You might be already knowing what pretty URL means and its importance in SEO. For example, this post is having a pretty URL i.e http://wapguy.com/creating-pretty-url-with-htaccess-mod-rewrite-for-better-seo . But this same post can also be accessed using the url http://wapguy.com/?p=349 . Now the pretty url are more effective than the later as pretty url clearly tells you what this page is about from the url itself. Moreover, the words in the URL might match the search keywords which helps in bringing more traffic from the search engines.
Now since this blog is powered by the awesome WordPress CMS its really easy for me to make the blog posts have pretty url structure. But for a PHP project or website, you will have to use the htaccess file mode rewrite inorder to make your link have a pretty URL structure.
Creating htaccess file:
Open NotePad > File > Save As > Choose the “Save as Type” to “All Files” > enter “.htaccess” as the name and press Save. You’ve created a htacces file.
Now paste the below codes into it.
Options +FollowSymLinks RewriteEngine On
The first line Options +FollowSymLinks is required for some server configurations.
Creating rewrite rules:
Now lets write the rewrite rules, We will go through some examples to understand these rules.
1) Rewriting topic.php?id=12 to topic-12.html
Options +FollowSymLinks RewriteEngine On RewriteRule ^topic-([0-9]+)\.html$ topic.php?id=$1
By using the above rewrite rules, whenever a user request for a url like topic-1.html the actual request given to the server would be like topic.php?id=1 and returns the page with that id.
2) Rewriting topic.php?id=3&name=MyPost to topic-3-MyPost.html
Options +FollowSymLinks RewriteEngine On RewriteRule ^topic-([0-9]+)-([a-zA-Z0-9_-]+)\.html$ topic.php?id=$1&name=$2
This would provide a more SEO friendly pretty url and contains the post name in the url.
3) Rewriting yoursite.com/user.php?name=xyz to yoursite.com/xyz
Options +FollowSymLinks RewriteEngine On RewriteRule ^([a-zA-Z0-9_-]+)\$ user.php?name=$1
There are many more things you can do with htaccess file, like you can deny access to files in your website, make redirects, disallow specific IP, user agent and so on..
But always remember to use the correct syntax and keep a backup of your working htaccess file before making up new changes because it can mess up your site.