September 12, 2013

Using mod_rewrite to make Blog URLs more SEO Friendly

Three3’s Question:

I am trying to turn my blog URLs into a more SEO friendly format using mod_rewrite. All of my articles are stored in a simple MySQL database. Each blog article url looks like this:

http://www.test.com/blog?id=20&category=online%20php%20tutorials&pagename=how%20to%20customize%20functions

I have managed to to make them look like this using mod_rewrite:

http://www.test.com/blog/online-php-tutorials/how-to-customize-functions/20

Here is my code that I paced in my .htaccess file:

RewriteRule ^blog/([a-z0-9-]+)/([a-z0-9-]+)/([a-z0-9-]+)/?$ /blog?id=$3&category=$1&pagename=$2 [L]

So what happens is this: When I click on the URL http://www.test.com/blog/online-php-tutorials/how-to-customize-functions/20, all of my CSS and images are not loading because it is trying to load them from a directory that does not actually exists. How would I load the files without having to create multiple directories that contain my sites CSS files and images?

Use root identifier / in your path. This will point the DocumentRoot of your server. Let me explain How this works

For an image like this:

<img src='test.jpg' /> 

Browser/Server will find it as http://www.test.com/blog/online-php-tutorials/how-to-customize-functions/20/test.jpg' but if you use / before the path

<img src='/test.jpg' />

It will look for it in http://www.test.com/test.jpg

Another Technique

Use full path in your files like:

<img src='http://test.com/test.jpg' />

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!