site en français

2011, Jun 19

Minimal urls using .htaccess

No more trailing .php on your website. To configure your .htaccess to have clean urls like http://bleezworld.com/engineering-blog, here is the solution.
It was a real pain in the ass to figure out how to so I hope this will be useful and save some time to lots of folks.

In this example, we suppose that we would like yoursite.com/xxxxx be treated by blog.php as if the real input was yoursite.com/blog.php?page=xxxx.

Options +FollowSymLinks
RewriteEngine On
RewriteRule ^blog/(.*)$ blog.php?page=$1 [L]
RewriteCond %{REQUEST_URI} !=/
RewriteCond %{REQUEST_URI} !news.xml
RewriteCond %{REQUEST_URI} !robots.txt
RewriteCond %{REQUEST_URI} !.php$
RewriteRule ^([^/]*)$ $1.php

This will turn the input yoursite.com/foo into yoursite.com/blog.php?page=foo. This will not rewrite the url to some static files (news.xml, robots.txt, …) nor the ones with .php already in the url.

Be careful about one thing : All servers don't have the same config so a .htaccess working locally might not work on your website. A few hints that could do the trick : place some slashs before points, parenthesis, ..., for instance replace xxx.php by xxx\.php. On certain servers, you will have to put a slash BEFORE page names (the resulting one, not the one triggering the rule) :

RewriteRule ^blog/(.*)$ /blog.php?page=$1 [L]
...
RewriteRule ^([^/]*)$ /$1.php

Play with your .htaccess parts by parts, comment out certain lines (with #) to debug and see what your server expects.

BleezWorld can perform missions for you. Consult us.