SEO friendly URLs with apache

  • Snippet Length: 15 minutes
  • Difficulty: Easy-Intermediate
  • Technologies: PHP, Linux System Administration, Apache

Here is my take on the popular apache mod re direct;

So your wanting your links to look readable by humans and search engines such as ; instead of

One way of doing this is telling Apache that when it encounters a certain url that is passed look for a different page.

Starting Point...

1. You can start by creating a .htaccess config in the root directory of the site via SSH;

nano .htaccess

2.Inside this .htaccess file enter the following below;

RewriteEngine on
RewriteRule ^news/([0-9]+)/(.*?).html$ news/index.php?id=$1

Lets break this down; "RewriteEngine On" basically just turns the setting on for this domain so that we can use the redirect ( pretty simple ).

The second line creates a rule that the directory we can look at is ^news/ so that would be /news/.

The next part /(0-9+)/ will only accept integers and wil be a virtual directory, this will be the id of the news item which is dynamically generated.

The next part (.*?).html$ will allow any text preceding .html which is a fixed element or the url. The $ dollar sign ends the first argument of the 2nd line.

Save & Restart Apache...

3.Save the config file (CTRL + X) and y to confirm then hit enter.

4.Restart apache it depends what version of linux your using most of the time you can just do

apachectl -k graceful


There's also a big debate as to whether or not search engines actually rank web pages higher because of the .html ending, I tend to stick with it because some research does suggest that search engines rank static content quite highly ( but this is constantly changing )

However the W3C are leaning more towards the removal of .html from links such as;

It's all really a matter of preference as I feel there is no real right answer at this moment.

My next snippet will show you how to create a function that will generate the friendly urls from the news title of the item (from database).

comments powered by Disqus