FREE THOUGHT · FREE SOFTWARE · FREE WORLD

Respond with 200 OK for 404 Not Found

Htaccess WizardWhat if you'd like to send a 200 OK response instead of the default 404 Not Found response using Apache .htaccess files or httpd.conf? One use would be to make sure upstream caches cache any request on an api server, as 404's are not cached.

Force a 200 Response with Mod_Alias

When a file isn't found by Apache, it will show the 404 Error configured by ErrorDocument. If we configure a specific URL request to return a 200 OK response using mod_alias Redirect, any request for that URL will just issue a 200 OK response. Then if we configure the ErrorDocument to point at that same URL configured to issue a 200 OK response, any 404 error will result in an internal request to that URL by ErrorDocument, and that internal request will cause the Redirect directive to take place - resulting in a 200 OK response for everything that usually returns a 404 Not Found.

  1. External user requests /missing-file
  2. Apache can't locate the file so it issues an internal request for /404
  3. Mod_Alias sees the request for /404 and issues a 200 OK to the user
Redirect 200 /404
ErrorDocument 404 /404

That will change the Apache ErrorDocument to the /404 file. But the Redirect line causes requests for /404 to issue a 200 OK response instead of a 404 Not Found.

Fix for Mod_Rewrite Rewrites

If that doesn't work it may be due to mod_rewrite no doubt. So if that's the case, add this under those first 2 lines but above any other rewrite lines in your .htaccess file:

Options FollowSymLinks ExecCGI

RewriteEngine On
RewriteBase /

# If the requested file is not an existing directory or file
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# need to add the ^4 in order to avoid triggering a loop
RewriteRule ^[^4]* /404 [L,S=4000]

More Info

Explained in more detail in Automate the ErrorDocument Triggering

Apache Htaccess 404 ErrorDocument Redirect

 

 

Comments