Make SEO Friendly URL in PHP by URL Re-Writing Using .htaccess File
27-06-2017
.htaccess is an Apache server configuration file that allows us to rewrite the URL. This file only has an extension and not any name.
Create a file name '.htaccess' in the root directory of your web application. Remember, this file has no name. It has only an extension as '.htaccess'. This is an Apache server configuration file that allows us to rewrite the URL.
Change index.php As Default Home Page Using .htaccess
The Index.php file of your root directory served as the home page of the application. But using .htaccess file, we can make any .php file to be served as the home page. In the below example code of . htaccess, I'm making customhome.php as the home page of the Application. This is very simple. just follow the below code in your .htaccess file
<IfModule dir_module>
DirectoryIndex index.php taohid78692.php
</IfModule>
RewriteEngine On
RewriteRule ^index.php customhome.php [NC]
RewriteRule ^index.html customhome.php [NC]
RewriteRule ^home customhome.php [NC]
Remove .php Extension From URL Using .htaccess
There are many advantages of removing .php extension from the URL. Our URL is pretty much SEO friendly and easy to read and remember. Also, our visitors of the application cannot guess the name of the actual file from which content is being served. In the below example code of .htaccess, we are serving contact-us.php file content as /contact.
RewriteEngine On
RewriteRule ^contact contact-us.php [NC]
Now we can access the URL as: yourapp.com/contact
Passing SEO Friendly URL Parameter Using .htaccess File
Usually, we pass URL parameters in PHP like: yourapp.com/user.php?name=taohid. Using .htaccess, we can remove the question mark(?) and keep it simple like: yourapp.com/user/taohid.
RewriteEngine On
###example of passing single URL Parameter
RewriteRule ^user/([\[\]=,\?&@~\{\}\+'\.*!™`0-9a-zA-Z-\s-']+) user.php?name=$1 [NC]
###example of passing multiple URL Parameter
RewriteRule ^page_name/([\[\]=,\?&@~\{\}\+'\.*!™`0-9a-zA-Z-\s-']+)/([\[\]=,\?&@~\{\}\+'\.*!™`0-9a-zA-Z-\s-']+) page_name.php?parameter1=$1¶meter2=$2 [NC]
In above example, We can pass any URL Parameter after user/your-url-parameter. And in user.php file, We can get the parameter value like : $_GET["name"];