URL Rewriting .php to .html

 

In this article you will learn how to reright your website URL from php to html or any other extension you want.

 

 

- Benefits of mod_rewrite

- Get pretty URLs
- Shortener website URLs
- Hide website variables (more security) 
- SEO, User-Friendly

 

- Check and enable Mod Rewrite

The first thing you want to do is make sure that you have mod_rewrite on our server.
By default, Apache has mod_rewrite installed, but not enabled. The easiest way to test if mod_rewrite is enabled on your server is to create a .htaccess file in a test directory such as yourwebsite.com/Test-Folder/  create .htaccess inside Test-Folder, copy and paste the following inside:
Options +FollowSymLinks
RewriteEngine On
Now attempt to browse to the subdirectory. One of two things could happen:
 
No errors:  Congrats mod_rewrite engine is now enabled.
500, Internal Server Error:  If you get this message then mod_rewrite was not installed/enabled on your server.
 
If you found that mod_rewrite was not installed on your server, google on how to enable mod_rewrite or contact your hosting provider.

 

- Example Goal

we want to use mod_rewrite to change our server URLs from PHP to HTML.


Dynamic URL: http://www.yourwebsite.com/profile.php?user=khalil (before writing)

Static URL: http://www.yourwebsite.com/profile/khalil.html (after writing)

 

Steps

A. Edit .htaccess file

 

Let's assume that this is profile.php source code: 

 

	

<?php 
$user=$_GET['user']; 

	.

	.


?>

We can browse users profiles by query $user  variable from the database like this:

http://www.yourwebsite.com/profile.php?user=khalil  -> This will get khalil's user profile page. 

 

The first step you should do is to edit your .htaccess file, so to rewright php to html in the above scenario : 

1- Create .htaccess file in your public_html folder (if not exists) 

2- Copy and paste this code 

 

<IfModule mod_rewrite.c>

RewriteEngine On

RewriteRule ^profile/([^/\.]+)/?.html$ profile.php?user=$1 

RewriteRule ^profile?.html$ profile.php

</IfModule>

 

First we enable mod_rewrite by : RewriteEngine On

create rule to rewrite website URLs from profile.php?user=$1 to profile/$1.html  ($1= any text) 

create rule to rewrite profile.php to profile.html  profile?.html profile.php

 

Now you can check the new website URLs by opening valid user profile with the new HTML path example : http://www.yourwebsite.com/profile.php?user=khalil

 

B. Edit your PHP anchors links

Now you need to modify your PHP files source codes by chaning anchors from PHP to HTML. 

for example one of your website anchores is 

<a hred="profile.php?user=khalil"> khalil </a> 

Change it to be : 

<a hred="profile/khalil.html"> khalil </a> 

 

 

Thats all, you are done. If you find this artice is usefull share it with your friends . 

 

 

Leave a comment