Justin Paul Silva

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:

.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> &copy;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.