Mod_rewrite search engine friendly urls

Last updated on November 18th, 2015 at 03:53 am

Click to rate this tutorial!
[Total: 2 Average: 5]

Search Engine Friendly URL’s

A typical component of a website is a ‘latest main’ database. Individual main items would be accessed as:

http://www.myweb.com/main.php?id=20090729

(a call to the main.php script passing a single GET parameter which identifies which item to display)

Now we introduce the RewriteRule:

RewriteRule ^main/([0-9]+) /main.php?id=$1

Translation:

* IF the request starts with main/ followed by one or more digits;
* THEN call the main.php script with the id parameter set to those digits.

The URI then becomes:

http://www.myweb.com/main/20090729

Or, because we left the RHS of the regular expression open, we can also use:

http://www.myweb.com/main/20090729.html

There is a slight problem here in that, if Content Negotiation is enabled, this URI could be taken as a call to the main.php script with the rest of the URL (/20090729.html) being unused. This is because there is no file called /main/20090729.html, and no file called /main, but /main.php does exist and Content Negotiation is all about finding that out. In that situation the correct main item won’t be displayed.

The solution? We could re-name the script, change the format of the URI, or turn off Content Negotiation (which you might want to do in any case), but there’s a simpler option:

RewriteRule ^main/([0-9]+) /scripts/main.php?id=$1

By moving the script into a sub-directory, which we can do now because it’s no longer called ‘in place’, we avoid any chance of conflict. The /scripts/ directory can, and should, now be secured to avoid direct access.

One of the major benefits of using rewrite rules and ‘hiding’ the script is that ONLY requests matching the regular expression can access it. In this case it’s not possible for someone to pass a non-numeric parameter, and any attempt would result, rightly, in a 404 Not Found response.

An even better rule in this case could be:

RewriteRule ^main/([0-9]{8}) /scripts/main.php?id=$1

or, if you want to be really strict and enforce the .html extension:

RewriteRule ^main/([0-9]{8})\.html$ /scripts/main.php?id=$1

Thanks 🙂

Click Here To See A Similar Tutorial.

Click to rate this tutorial!
[Total: 2 Average: 5]

Leave a Reply

Your email address will not be published.