Apache rule based on http status and on response status

I want to create an apache rule based on the user agent AND on the http response.

For example, I want a rule that says: if user-agent=test and the status of the request based on this user agent=503, redirect the request to /home

On the documentation page, I found a variable for based on the user agent(HTTP_USER_AGENT), but nothing for the http status. Is that possible?


Solution 1:

You could do something like the following, to define a custom 503 "error document" when a request with the User-Agent "test" is sent:

<If "%{HTTP_USER_AGENT} == 'test'">
    ErrorDocument 503 https://example.com/home
</If>

When an absolute URL is used in the ErrorDocument directive, it will trigger a 302 (temporary) redirect to that URL should the stated HTTP response status be triggered by Apache.

So, the above will issue an external redirect to /home when a request with User-Agent "test" triggers a 503 response in Apache.

This will need to be defined in the main server config (not .htaccess) to stand a chance of catching an arbitrary 503 generated by the server. Although it is questionable whether this would catch such an "unexpected" error since a 503 - if triggered by the server itself - is a rather serious/fatal error. Ordinarily, a 503 is a controlled response for when the application goes into "maintenance mode". In this scenario, you would arguably handle this differently.

Alternatively, the REDIRECT_STATUS environment variable holds the HTTP response status code so you could do something like the following using mod_rewrite to override the ErrorDocument and trigger a 302 redirect to /home:

RewriteEngine On    

RewriteCond %{ENV:REDIRECT_STATUS} =503
RewriteCond %{HTTP_USER_AGENT} "=test"
RewriteRule ^ /home [R=302,L]

If the 503 is triggered by the application itself (eg. in PHP) then this will not be caught by the above rule(s).