How to Generate User Friendly URL using .htaccess and PHP

The pretty URLs makes webpage URL user-friendly and human readable. It also called SEO friendly URLs and help to improve search engine rankings. Using htaccess file, you can easily create user-friendly URL in the web application.

To make URL SEO friendly or user-friendly, you need to create a .htaccess file and define some rewrite rules. The URI segments values can be easily retrieved using PHP. In this tutorial, we will show you a simple way to generate user-friendly URL with .htaccess and PHP.

.htaccess file:
Create a .htaccess file in the root directory and define the RewriteRule.

RewriteEngine On
 
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
 
RewriteRule ^.*$ ./index.php

Retrive URI Segments using PHP
The following code retrieve the URL segments and returns as an array.

$uriSegments explode("/"parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));

Assume that your user-friendly URL is http://www.example.com/codex/foo/bar. You can get the URL segments value like the following.

echo $uriSegments[1]; //returns codex
echo $uriSegments[2]; //returns foo
echo $uriSegments[3]; //returns bar

4 Comments

  1. Marcelo Albuquerque Said...
  2. Arun Said...
  3. Rahul M Said...
    • CodexWorld Said...

Leave a reply

keyboard_double_arrow_up