Search code examples
phpapache.htaccessmod-rewriteerrordocument

ErrorDocument & Mod Rewrite


I was wondering if there is a way to use Mod Rewrite to handle every possible http status error code (4XX and 5XX ones) instead of declaring them all in htaccess like this:

# serve custom error pages
ErrorDocument 400 error.php?code=400
[...]
ErrorDocument 510 error.php?code=510

Somewhere around I found this little trick:

# provide a universal error document
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ error.php [L]

But isn't it handling only 404 ones? If it's ok, how can I modify my cache busting rewrite rule to also make it handle this feature?

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)\.\d+\.(css|js)$ $1.$2 [L]

I would need something like:

IF %{REQUEST_URI} MATCHES "^(.+)\.\d+\.(css|js)$"
    REWRITE TO "$1.$2"
ELSE
    REWRITE TO "error.php"

Can you help me please? Many thanks!


Solution

  • Are you expecting some new wave of HTTP Status Codes to hit the web in the near future that you can't just make a list of 10 or so error codes that point to the correct corresponding documents? You really should just go through the List of HTTP status codes and pick out which ones your server would actually use and set error documents for those ones. An ordinary web server would probably only ever see a 404 and a 500, maybe a 403 if it the permissions weren't configured correctly, and maybe a 509 if you're on a shared web service (although I think that one is handled by the hosting provider anyways). If you're not building some very advanced web server that can do a whole lot of different things, you're just wasting your web server's microscopic time looking for all those error codes it will never use.

    But seriously, don't list every single status code from 400 to 510. Seriously. A lot of those would be status codes you'd manually send from the executing script when it determines something is wrong.