srijeda, 28. studenoga 2007.

Typicall problem with server error page 404

When running PHP as a CGI binary on Apache, you might get the above error if you request a nonexistent PHP file. If you've got a custom 404 page (or even the default one), this can be irritating, as it makes for an inconsistent user experience (although a good site (re)design should never be a catalyst of 404 errors).

The reason this happens is that any requests ending in .php are simply handed off to the PHP executable without verifying that such a file exists. Although this is by design, it can be a bit offputting. Unfortunately, there does not appear to be a way to configure the PHP executable to return a "normal" 404 to Apache if the requested script does not exist. True, it does return a 404 response header along with the "No input file specified", but it won't return the appropriate ErrorDocument under any circumstances.

Google didn't come up with any solutions, although it did find many other people with the same problem.

Luckily for me, I had spent the last few days playing around with mod_rewrite, and it occurred to me that that's how to solve the problem. Mod rewrite is an extremely powerful Apache module that lets you manipulate/redirect urls. In short, if you want to prevent hotlinking, protect content, optimize for search engines, do load balancing, or just about anything you can think of when it comes to urls, then mod_rewrite is for you.

So getting back on topic, all we have to do is create a simple rewrite rule that checks the requested url to see if 1. it is ends in .php and 2. no such file exists. If both conditions are met, we translate the request into a url that we know doesn't exist. This triggers a 404, and Apache sends the client the appropriate ErrorDocument. Rewrite rules are run before anything is sent off to the content handler, so PHP is bypassed entirely.

It's simply a matter of putting an .htaccess file in our base dir with the following lines:

RewriteEngine On
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
RewriteRule ^.+\.php$ /bogusfile

And that's it! Your mileage may vary, since not all servers are configured identically. Just be sure that /bogusfile really doesn't exist, otherwise it will be served up instead of the 404.

Update 2005-01-20 10:55 AM
It appears my google skills are lacking. Someone known as n74 solved this about two months ago ... here and here...

The only difference is that his solution rewrites the url to the ErrorDocument, whereas mine rewrites it to a nonexistent file.

The end result is the same, except that his way a 200 status code is sent rather than a 404.

Nema komentara:

 

Sopranos Ruby Css Xhtml Cgi Asp.net Calabria Rocky Oktoberfest Fencing