Simplify your URLs
I hate long URLs. Hell, I even hate extensions on my pages.
For some sites I've done, I did not want to have a bunch of individual pages:
- /index.php
- /help.php
- /about.php
I wanted to use Smarty, a template engine for PHP, but without having to create individual PHP files and without long URLs (/index.php?page=about).
So, in my index.php file:
<?php
$smarty = new Smarty();
list ($page,$query) = explode("?",$HTTP_SERVER_VARS["REQUEST_URI"]);
$page = basename($page, ".php");
$smarty->assign('page', $page);
$smarty->display('index.tpl');
?>
(I stripped a bunch out, of course. For example, you never want to take what a user tells you at face value! My index.php file cleans up $page and compares it against a list of valid pages before doing anything else.)
Then, in index.tpl, I have a basic structure in place and I use Smarty's {include} function to include 'page' in the correct location:
<html>
<head>
<title>Common Title - {$page}</title>
</head>
<body>
Some common content, perhaps.
{include file="$page.tpl"}
</body>
</html>
And, then, to get rid of index.php… so that /about loads the about.tpl content, etc, in .htaccess I have:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.mydomain\.com$ [NC]
RewriteRule ^(.*)$ http://mydomain.com/$1 [R=301,L]
RewriteCond %{SCRIPT_FILENAME} ! -f
RewriteCond %{SCRIPT_FILENAME} ! -d
RewriteRule ^(.+)$ /index.php?$1 [PT,L,QSA]
</IfModule>
That first part, where I redirect www.mydomain.com to mydomain.com, is because 'www.' is redundant and its use has been deprecated!
The second part has the bits that are relevant to this post…
RewriteCond %{SCRIPT_FILENAME} ! -f
RewriteCond %{SCRIPT_FILENAME} ! -d
If the user is requesting an actual file or directory, then we won't try to rewrite the URL of the request to meet our own perverted neatness requirements.
RewriteRule ^(.+)$ /index.php?$1 [PT,L,QSA]
The URL that the user requested, not being an actual file or directory, is rewritten to be a query string to index.php.
So, for example, if the user requested http://mydomain.com/about, this rewrite would cause Apache to serve up http://mydomain.com/index.php?about (without rewriting the address in the browser). index.php would parse the string, set $page = 'about' and load up the index.tpl Smarty template. Smarty would parse the template and include about.tpl.
There! That was overly complex and convoluted, but at least my URLs remain short and I can add new pages (or update common bits of code) without a bunch of copying, pasting, and editing. And that makes me happy.
Post a comment
You must be logged in to post a comment.