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
Thanks for the help.
My suggestion is to remove the first value from array return, in this case: “$uriSegments[0]”. This value is empty in all requests.
We can use the array_shift function to remove this value:
$uriSegments = explode(“/”, parse_url($_SERVER[‘REQUEST_URI’], PHP_URL_PATH));
array_shift($uriSegments);
Now, the “$uriSegments[0]” returns “codex”
How this htaccess works in windows server?Please give one example for user friendly url.
will it work on HTTP site also?
Yes.