Categories: Development

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 {

}

 

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago