Simple pretty URL’s with PHP and the htaccess file

An easy method of doing simplified or pretty URLs with PHP and a htaccess file. Using prettified URL’s looks good, clean, helps readability and is a positive for SEO.

Two examples of prettified URL’s vs conventional:

https://domain.com/users/index.php?id=hunter123

vs

https://domain.com/users/hunter123

Or an even more extreme case:

https://domain.com/products/index.php?category=clothing&type=shorts

vs

https://domain.com/products/clothing/shorts

 

Instructions

Doing pretty or simple URL’s isnt hard, all thats required is a .htaccess file or editing your existing one.

.htaccess in the root folder of the domain:

Options +FollowSymLinks
RewriteEngine On
RewriteRule ^(.*)$ index.php?id=$1 [QSA]

This means anything after the slash “/” in the URL will be a string for $_GET['id'].

index.php file:

<?php
$url_data = explode("/", $_GET['id']);
echo json_encode($url_data);

This will put the string into an array based on the “/” position.

https://domain.com/alpha/bravo/charlie

Will output

["alpha","bravo","charlie"]

Now you can work with the virtual directory depth (/) and have pretty URL’s without having the actual folder structure.

This example being for

https://domain.com/users/hunter123

This URL has the base directory of users and then a pointer to get specific data, in this case it is for the user “hunter123”

if (count($url_data) == 1) {
    $base_dir = $url_data[0];//users
    if ($base_dir == 'users') {
        //Show users homepage
    } else {
        //.....
    }
} else {
    $base_dir = $url_data[0];//users
    $pointer = $url_data[1];//hunter123
    if ($base_dir == 'users') {
        //Get and show hunter123 data
        //.....
    } else {
        //.....
    }
}

As this is only a simple guide there are no checks for if the data exists else redirect back and make sure to be using prepared MySQL statements.

If you want to show the homepage run a conditional check such as:

if (empty($url_data[0])) {
    //Show homepage
} else {

}