Search code examples
apache.htaccess

.htaccess - How do I capture the incoming request`s HTTP Status Code?


You know how Apache has many server variables like %{REQUEST_URI}, and %{ENV:REDIRECT_STATUS}

What is the variable name for the current request's HTTP status code?

I ask this because I want to write a RewriteCond that says 'if the HTTP status code is 302, then...'. But I cannot figure out what the server variable for this would be.

Your help would be greatly appreciated!


Solution

  • There is no such thing as a request status code. Only the response, sent back from the server to the client, has an HTTP status code.

    The closest you can do is setting a Custom Error Responses via an ErrorDocument directive. This means, based on some status code e.g. 404, you can call some server side script, which acts appropriately.

    ErrorDocument 404 /var/www/html/errors/handle_404.php
    

    This works for status codes starting with 400 and 500, but not for response codes in the range of 200 or 300. See again Custom Error Responses

    Customized error responses can be defined for any HTTP status code designated as an error condition - that is, any 4xx or 5xx status.


    Addressing comments, the syntax of ErrorDocument is defined as

    Syntax: ErrorDocument error-code document

    So there is just the error-code (4xx-5xx) to handle, and some document to show or execute, no way to define any additional flags.