htaccess rewrite if redirected file exists htaccess rewrite if redirected file exists php php

htaccess rewrite if redirected file exists


you should be able to achieve that by using two conditions:

RewriteCond %{REQUEST_FILENAME} (.*)\.html$RewriteCond %1\.php -fRewriteRule ^(.*)\.html$ $1.php [R,L]

The first condition checks if the filename ended with .html and the second uses the back reference %1 from the first condition to check if .php version exists.

Hope it helps. :)


I'm sorry to answer sooooo late but you will need to add the RewriteBase directive to make it works.

I had the same problem (with your http:/stufff) and fixed it this way :

RewriteBase   /your/application_pathRewriteCond %{REQUEST_FILENAME} (.*)\.html$RewriteCond %1\.php -fRewriteRule ^(.*)\.html$ $1.php [L]

Hope it will help !


I also wanted to Rewrite all .html request to .php files, but only if the .php file exist. But my variation was that this should only happen if the actual .html file does not exist.

So only calls to .html files that does not exist is Rewritten to .php file, if they do exists by these rules: (I also have tested this on a XAMP local server and also a Apache online server with success!)

# Rewrite rules to .html file to .php if the .php version# does actually exist.RewriteCond %{REQUEST_FILENAME} (.*)\.html [NC]RewriteCond %{REQUEST_FILENAME} !-f [NC]RewriteCond %1\.php -f [NC]RewriteRule ^(.*).html$ $1.php [NC]
  1. It first check if the requested file is a .html file (we don't want .jpg, .css, .pdf, etc. to be rewritten).
  2. The it checks if that .html file does not exist. (we don't want to rewrite to .php if it actually does exist.)
  3. Then it checks if a .php version does exist (we don't want to rewrite to a non existing .php file).
  4. Then it rewrites the .html to .php