3

I've beens scratching my head trying to get this to work but I haven't be able to.

I need to redirect all html pages to php pages, all with the same name except the extension but only if the php version exists.

So if a page is "products.html" i need it to check if "products.php" exists, if it does, execute the php version (without redirecting the browser and showing products.php) if it doesn't, render the html version

Can this be done using htaccess? if so, could you help me with an example or point me to where i can find examples of this?

Side Note: I need to do this with both .html and .htm pages.

I also tried making html pages execute php code using the AddType and AddHandler examples i found online but none of them worked for me so that's why i decided to use php versions of each page instead.

Thanks.

anubhava
  • 761,203
  • 64
  • 569
  • 643
Nero F Rox
  • 49
  • 5

3 Answers3

2

Put this code in your DOCUMENT_ROOT/.htaccess file:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.+?)\.html?$ /$1.php [L]
anubhava
  • 761,203
  • 64
  • 569
  • 643
-1

You can set a rewrite rule to index.php, within the index.php file check if the file exist and serve it by using include($page);

$file = $_GET['page'];

if (file_exists($file)) {
    include($file);
} else {
    // 404 page...
}
Joran Den Houting
  • 3,149
  • 3
  • 21
  • 51
-2

Your answer is solved here: htaccess rewrite if redirected file exists

The solution is a condition for your rewrite. It can be placed in the .htaccess of your root folder or just the folder where you want this feature.

RewriteCond %{REQUEST_FILENAME} (.*)\.html?$
RewriteCond %1\.php -f
RewriteRule ^(.*)\.html?$ $1.php [P,L]

The only difference versus their answer is P as I have made your request an internal redirect to show the old URL to the user. Also, I use html? to get htm and html file.

This is described at https://httpd.apache.org/docs/current/mod/mod_rewrite.html

Community
  • 1
  • 1
William Entriken
  • 37,208
  • 23
  • 149
  • 195