3

When I try to remove my PHP extensions from all my files using my .htaccess file on my Apache server, everything works great. The extensions are removed, and everything looks much better.

However, I'm having one small issue: when I would normally go to a page such as ./nonexistent.php, I would get a 404 error. But, when I rewrite my URLs, and I go to ./nonexistent, I instead get a 500 Internal Server Error.

Ideally, I would like to simply redirect my user to a custom 'Page Not Found' page, but I can't currently find a way to do this.

Here's 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, this doesn't seem to have an effect either.

So, to conclude, does anyone know how to rewrite extensions, while maintaining the same functioning of the 'Page Not Found' system that is the default?

elliottbolzan
  • 1,057
  • 1
  • 15
  • 30

2 Answers2

2

When you are requesting a non-existent file using the above rewrite conditions, you are running into an infinite redirect.

If you access http://yoursite.com/i-dont-exist, the first condition is evaluating true, i-dont-exist is a non existent file, so it will try to rewrite to i-dont-exist.php which also doesn't exist so the rewrite pattern continues until Apache limits the recursion and gives you a 500 error (essentially it is continually rewritten to i-dont-exist.php.php.php.php.php...php until you encounter the 500 error.

You can resolve this by adding an additional check to make sure the file with the .php extension exists before rewriting.

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f  #make sure $1.php exists before rewriting
RewriteRule ^(.*)$ $1.php

If the file.php exists, then it will rewrite to it, otherwise it will not, and the 404 error page will be served.

drew010
  • 68,777
  • 11
  • 134
  • 162
  • drew010, you are right, the other answer is practical because it dismisses my problem, but doesn't actually fix it. – elliottbolzan Mar 25 '12 at 22:13
  • If you check your Apache `error_log`, you will see the exact cause of the 500 error. If you have a very busy site, you will be writing to your error log a lot and making it grow unnecessarily which makes it harder to find and debug actual errors. See if this helps as well. – drew010 Mar 25 '12 at 22:14
1

http://www.openia.com/blogs/errordocument-and-mod_rewrite-workaround

Thom Wiggers
  • 6,938
  • 1
  • 39
  • 65
  • Awesome answer, I simply had to replace `ErrorDocument 500 /nope` with `ErrorDocument 500 http://path.com/to_nope`. – elliottbolzan Mar 25 '12 at 22:09
  • 1
    You shouldn't be getting a 500 internal server error in the first place. Overriding the 500 error page is a workaround but is not solving the problem. – drew010 Mar 25 '12 at 22:11