Clean URLs with htaccess
Posted on
Here’s a bit of code I use on most of my smaller sites, including this one, to clean up the URLs. This is the simplest way I know how to do it. A few benefits of clean URLs:
- They just look nicer and more professional
- They’re easy to read and remember
- The average web user doesn’t care about webpage file extentions, nor should they
- It hides the underlying technology
- The URLs become more SEO friendly
- It allows you to use cleaner code
.htaccess
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^/?$ index.php?page=home&%{QUERY_STRING} [L]
RewriteRule ^([^/\.]+)?$ index.php?page=$1&%{QUERY_STRING} [L]
</IfModule>
index.php:
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
<title>My Site - <?= $_GET['page'] ?></title>
</head>
<body>
<header>
<h1>My Site</h1>
<nav>Navigation goes here</nav>
</header>
<section>
<?php include($_GET['page']) ?>
</section>
<footer>
©Justin Paul Silva
</footer>
</body>
</html>
With this, you can go to mysite.com/portfolio, and you will see mysite.com/portfolio.php wrapped in index.php’s header and footer.
This way, the header and footer will be added to every page without having to use include or require on each one. Remember the DRY principle.