Mod_Rewrite Eliminate Shift Changes Functioning 404
When I try to remove my PHP extensions from all of my files using my .htaccess file on my Apache server everything works fine. The extensions are removed and everything looks much better.
However, I have one small problem: when I normally go to a page like ./nonexistent.php
I would get a 404 error. But when I rewrite my urls and I go to ./nonexistent
, I get instead 500 Internal Server Error
.
Ideally, I would like to just redirect the user to a custom Page Not Found page, but I am currently unable to find a way to do this.
Here is the code I'm using:
Options -MultiViews
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ $1.php
I've tried setting: ErrorDocument 500 /nope
however that has no effect either.
So, to conclude, does anyone know how to rewrite extensions while still keeping the Page Not Found system functioning the same as the default?
When you request a non-existent file using the above overwrite conditions, you trigger an infinite redirect.
If you access http://yoursite.com/i-dont-exist
, the first condition evaluates to true, i-dont-exist
it is a file that does not exist, so it will try to rewrite to i-dont-exist.php
which also does not exist, so the rewrite pattern continues until the Apache recursion limits are set and gives you a 500 error (essentially , it constantly overwrites i-dont-exist.php.php.php.php.php...php
until you encounter a 500 error.
You can fix this problem by adding an extra check to make sure the file with the extension .php
exists before being overwritten.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f #make sure $1.php exists before rewriting
RewriteRule ^(.*)$ $1.php
If it does exist file.php
, it will rewrite to it, otherwise it won't and the 404 error page will be served.
http://www.openia.com/blogs/errordocument-and-mod_rewrite-workaround