Cleaner URLs in PHP with Apache
URLs are very important for user experience and are part of the recipe for successful SEO. To create this Website, I wanted to keep things very simple and I built the code around the simplest solutions in PHP. I tried and applied a simple and very satisfying solution to have cleaner URLs without using any framework. It's a simple Apache configuration using mod_rewrite in 2 lines.
All this technique really does is rewriting any request that does not have an extension and adding .php
to it. What this means is you can have a URL like
http://www.richardvallee.com/techshares/cleanerurlsinphpwithapache
while all you need is to have a file named cleanerurlsinphpwithapache.php in a techshare directory of your Web directory.
Obviously this is not groundbreaking in any way. But it does allow the simplest php sites that do not use any framework to remove the .php
extension from their
URL. Not that it's really damaging or shameful to display, but it is unnecessary to the user and so superfluous to the URL. This trick is often used to
rewrite a .php
extension as .html
. But the .html
extension is just as superfluous to the user as .php
.
You first need to have mod_rewrite installed. On a shared host, it should be installed. If you manage your own server, it's usually simple to install using your distribution installer (aptitude, yum, rpm, etc.).
The all you need are the 2 following Apache instructions:
RewriteEngine On
RewriteRule ^([^\.]+)$ $1.php
All these 2 instructions do is:
- enable the rewrite engine
- modify any request that is missing a
.
by adding.php
to it
To the user, this is completely transparent. A very basic structure can be built with this for more semantic URLs. More complex rules are needed for catalogs and other dynamic listings, but solutions can be mixed.