Simple Pretty URL Using PHP htaccess (Step-By-Step Example)

Welcome to a quick tutorial on how to create a pretty URL system with PHP and htaccess. Yes, having file extensions in the URL is ugly and it looks totally unprofessional. If you are looking to create clean, human-friendly URLs, it actually isn’t that difficult to achieve.

A simplified WordPress inspired pretty URL system with htaccess and PHP can be achieved with the following steps:

  • Set the htaccess to redirect all requests to the index page – RewriteRule . /index.php [L]
  • Parse the path section of the URL in the index page – $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
  • Finally, load the requested page accordingly – require implode($path, "-") . ".php";

That covers the basics, but just how is this done exactly? Let us walk through a simple example in this guide – Read on to find out!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Pretty URL Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

  • Open Apache httpd.conf, enable URL rewrite.
  • If not deployed in the base path, for example, http://site.com/PRETTY-URL/:
    • Edit .htaccess, change to RewriteBase /PRETTY-URL/ and RewriteRule /PRETTY-URL/ index.php [L].
    • Edit index.php and set $base = "/PRETTY-URL/".
If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

 

PRETTY URL WITH HTACCESS & PHP

Let us now get started with creating a pretty URL system with Apache Web Server and PHP.

 

STEP 1) ENABLE URL REWRITE

httpd.conf
# Make sure that mod rewrite is enabled
LoadModule rewrite_module modules/mod_rewrite.so

# Make sure that AllowOverride is enabled
<Directory "D:/YOUR-HTTP-FOLDER">
  AllowOverride All
</Directory>

First, open the Apache httpd.conf file, and make sure that the URL rewrite module is enabled. Also, ensure that overriding is allowed.

 

STEP 2) HTACCESS – REDIRECT EVERYTHING TO INDEX.PHP

.htaccess
# CHANGE REWRITEBASE AND REWRITERULE ACCORDINGLY IF BASE IS NOT "/"
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

Next, create a .htaccess file in your project folder. That’s right, for you guys who have used WordPress before, look no further – This is exactly what WordPress does. What these mean in plain English:

  • Redirect everything to index.php .
  • But leave the existing files and folders be.

The whole idea here is to use PHP to load the requested page (or even fetch contents from the database).

 

 

STEP 3) PHP PAGE LOAD HANDLER

index.php
<?php
// (A) PARSE URL PATH INTO AN ARRAY
// (A1) EXTRACT PATH FROM FULL URL
// E.G. http://site.com/foo/bar/ > $path = "/foo/bar/"
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

// (A2) REMOVE BASE FOLDER FROM PATH
// E.G. "/foo/bar/" > "foo/bar/"
$base = "/";
if (substr($path, 0, strlen($base)) == $base) {
  $path = substr($path, strlen($base));
}

// (A3) EXPLODE INTO AN ARRAY
// E.G. "foo/bar/" > ["foo", "bar"]
$path = explode("/", rtrim($path, "/"));

// (B) LOAD REQUESTED PAGE ACCORDINGLY
// (B1) FOR "SINGLE SEGMENT" PATH
// E.G. http://site.com/ > [""] > index.html
// E.G. http://site.com/foo/ > ["foo"] > foo.html
if (count($path)==1) { 
  $file = $path[0]=="" ? "index.html" : $path[0] . ".html"; 
}

// (B2) FOR "MULTI-SEGMENT" PATH
// E.G. http://site.com/foo/bar/ > ["foo", "bar"] > foo-bar.html
else { 
  $file = implode($path, "-") . ".html"; 
}

// (B3) LOAD REQUESTED FILE FROM PAGES FOLDER OR SHOW 404 ERROR
$folder = __DIR__ . DIRECTORY_SEPARATOR . "pages" . DIRECTORY_SEPARATOR;
$file = $folder . $file;
if (file_exists($file)) { require $file; }
else {
  http_response_code(404);
  require $folder . "404.html";
}

With all the requests redirected to the index page, the next step is… Captain Obvious. We need to create a script that will fetch and serve the pages accordingly. This simple page handler should be straightforward enough to understand – We extract the path from the URL and load the respective HTML page. For example, http://site.com/foo/bar/ will load pages/foo-bar.html.

 

 

STEP 4) HTML PAGES

With the foundations all in place, all that’s left is to create a “pages” folder and add some pages inside.

 

HOME PAGE

pages/index.html
<h1>HOME PAGE</h1>
<p>The dummy home page.</p>

 

ABOUT PAGE

pages/about.html
<h1>ABOUT PAGE</h1>
<p>The dummy about page.</p>

 

404 PAGE

pages/404.html
<h1>PAGE NOT FOUND</h1>
<p>Opps. Page might have been abducted by aliens.</p>

 

 

STEP 5) PROTECTING THE PAGES FOLDER

pages/.htaccess
Deny from all

Users can still manually access the pages from the URL, for example, http://site.com/pages/about.html. So a small extra here, create a .htaccess file in the pages folder to deny public access.

P.S. PHP is still able to read and access the pages folder.

 

USEFUL BITS & LINKS

That’s it for the pretty URL system, and here are some extras that you may find useful.

 

A SMALL NOTE ON INDEX.PHP

The above is but a simple example of how page load can be handled in PHP. There are endless ways to do it, and here are a few more ideas:

  • Part B can be modified to use an HTML template – require "HTML-TOP.PHP"; require "PAGE.PHP"; require "HTML-BOTTOM.PHP";
  • Or even load from a database – require "HTML-TOP.PHP"; require "PAGE-LOAD-DATABASE.PHP"; require HTML-BOTTOM.PHP;
  • For you guys who might be working on an eCommerce project, the path can be used to serve as the category or pagination. For example, http://site.com/pastas/3. $path[0] is the category, and $path[1] is the page number.

So yes, feel free to change it however you see fit in your project.

 

HOW ABOUT OTHER WEB SERVERS?

If you are using IIS or NGINX – It is possible to achieve this as well. Just enable URL rewrite and “translate” the above .htaccess for your web server.

 

LINKS & REFERENCES

 

INFOGRAPHIC CHEAT SHEET

Pretty URL With PHP htaccess (click to enlarge)

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope it has helped you to create a better website, and if you have anything to add to this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *