April 27, 2021 0 Comments

Last Updated on April 27, 2021 by amitoverflow1

htaccess .php to .html

In this article you will learn how to use RewriteRule 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.

The htaccess RewriteRule example being used in this article is a 100 percent workin code example , so you can modify it as per your requirement or just copy and paste it direct to your htaccess-tutorial-for-beginers 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 .

This rewrites /foobar.html to
/foobar.php .
The condition

RewriteCond %{REQUEST_FILENAME} !-f

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 as the rule above doesn’t do this.

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

RewriteCond %{ENV:REDIRECT_STATUS} ^$
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 location which can create SEO problems for you.

Here is it all together .

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

Related post : URL Rewriting tutorial for beginners

Leave a Reply

Your email address will not be published. Required fields are marked *