Last Updated on August 2, 2021 by Amit

htaccess .php to .html

In this article you will learn how to use RewriteRule directive in an htaccess file to change .php extension to .html .
This article is for Aache mod-rewrite beginners who want to improve their URL-rewriting skill and learn how it can be done using htaccess. If you want learn htaccess from the scratch you can follow this tutorial URL Rewriting tutorial for beginners

The htaccess RewriteRule code examples being used in this article are 100 percent working , so you can modify them as per your requirement or just copy and paste it direct to your file.

Converting .php into .html

If you want to convert your .php URLs into .html , you can do this with a RewriteRule in an htaccess file.
Here I will show you how simple it is and how you can convert your php extension into html.

The following RewriteRule is a simple but powerful code example to rewrite your .html URL to .php .

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+?)\.html$ /$1.php [L]

The code above will map your .html URLs to .php .

With the rule above a request for /file.html will work as if it was a request for /file.php .
The rule does not conflict with your existent .html files meaning that if you have .html files in your directory then those files won’t get effected by the rule.
To keep the existent html files safe , we use the following the following condition in our rule

RewriteCond %{REQUEST_FILENAME} !-f

It prevents your existent .html files from being rewritten . This condition is important otherwise if you remove it then your other html files that exist will also map to the .php version.

Okay, sounds cool! With the rule above you can just type file.html instead of file.php to access the php file.

But there is still one important thing that needs to be implemented.

You need one more rule to redirect your .php URLs to .html extension as the rule above doesn’t do this. The rule above works perfectly fine but it leaves you with two different URLs /file.html , /file.php pointing to the same location.

You can 301 Redirect your .php URLs to include the .html extension using the following rule :

RewriteRule ^(.+?)\.php$ /$1.html [R=301,L]

This 301redirect rule is important because if you just use the first one then there will be two different URLs pointing to the same file which can create SEO problems for you (Duplicate content ).

Here is it all together .

RewriteEngine on
RewriteRule ^(.+?)\.php$ /$1.html [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+?)\.html$ /$1.php [L]

Related post : URL Rewriting tutorial for beginners

How useful was this post?

Click on a star to rate it!

Average rating 4.5 / 5. Vote count: 86

No votes so far! Be the first to rate this post.