.htaccess to redirect all unknowns to a .php file


I used .htaccess to redirect all unknown web pages to a php file which then displayed the correct content based on the page requested. This allowed me to have virtual directories. domain.com/contact etc. The php file then pulled the correct content from the database based on the directory name.

I used ErrorDocument 404 /file.php
However this stops them being indexed by search engines as 404 is ignored…

How should this be done?

Help appreciated



Well, as an error handler, you’ve got the correct code. In fact, your method is the same (albeit, with different code) as WordPress (which uses mod_rewrite to test for the existence of a file or directory then redirects EVERYTHING to its own index.php script).

As for two different ways of doing the same thing, I use extensionless URIs on my own website and use mod_rewrite to add the .php extension. On one client’s website, I use the article title and redirect to the script to fetch the article based on the URI (or back to the Home Page if not found).

There are lots of ways to do this and, technically, yours is correct. The only problem with using ErrorDocument is that you’re sending a 404 response (not a good thing) with every redirect to your file.php.



Thanks David,

I’ve managed to get this done and placed the following in the .htaccess file and it seems to work ok in redirecting all unknowns to my file.php.

I’ve disabled the 404 error document.

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /file.php [QSA,L]


You don’t need the QSA (that’s done automatically UNLESS you create a new query string in the redirection).