Search code examples
apache.htaccessanti-bot

Apache htaccess return 404 code even if page exists without using rewrite mod:


To protect my server from bots, I want to return a 404 error page if certain files are requested EVEN IF THEY EXIST but without using the rewrite mod. It is possible?


Solution

  • You can use a mod_alias Redirect (or RedirectMatch) directive.

    For example:

    Redirect 404 /file1.html
    Redirect 404 /file2.html
    

    This doesn't actually trigger a "redirect", as in an external 3xx redirect. It sends the stated 404 response if one of the URLs is requested (regardless of whether that file exists or not).

    Reference:

    If there is a pattern to these URLs then use a RedirectMatch directive instead, which matches against a regex rather than using simple prefix-matching. For example, to serve a 404 for all requests to the /secret subdirectory (and all files within) then use the following:

    RedirectMatch 404 ^/secret($|/)
    

    To customise the 404 response use an ErrorDocument directive:

    ErrorDocument 404 /error-docs/404.html