I would like to do a 404 redirect with Apache, and I find several solutions:
The .htaccess method. But I don't want to add a .htaccess if not necessary.
virtual host method:
<VirtualHost *:80> ServerAlias *.example.com Redirect 404 /index.html ErrorDocument 404 /index.html </VirtualHost>
I would like to know what's the difference Redirect 404 and ErrorDocument 404?
Did you test with
Redirect
directive?Redirect 404 /index.html
means that a 404 response will return when the client request/index.html
(even if it could possibly exist).ErrorDocument 404 /index.html
means that when the client access a non exist URL, Apache will redirect to index.html page.You must use
ErrorDocument
in this case.The two are generally unrelated. When I just tried to set up a redirect with a 404 status I got the error message
Redirect URL not valid for this status
when trying to start apache.A Redirect sends the client to a new address and provides a status for the client. The status returned are usually 30x values.
The ErrorDocument directive configures apache to return a particular page (rather than the default page) when an error of type nnn occurs. In your example you are saying return /index.html when a 404 (Not Found) error occurs.
What are you trying to achieve ?
If you configure the
ErrorDocument
directive correctly, all you have to do is make sure the file is not actually present. If you are trying to match a filename pattern, then you need to match the pattern and rewrite the request to a non-existant response. And make sure to turn off directory browsing:These are 3 different things:
Where you configure your directives:
Most directives, you can put in either file. The directives in .htaccess always apply to the current directory. You can put them in the web root or in a subdirectory. Changes in the Apache config require a reload of the webserver (which is a good thing because it does some checks too). It is usually recommended to not use .htaccess at all (if you don't have to) for performance reasons.
In the context where you define the directive, if in
<VirtualHost *:80>
it is in virtual host context (meaning it applies for this virtual host). You can also use Directory context, meaning it applies to a specific directory only. This is explained quite well in the Apache 2.4 "Configuration Sections" docs. .htaccess applies to specific directories (or all if you put it in the top level).How you configure, meaning which directives. ErrorDocument and Redirect do different things:
ErrorDocument 404 error.html
. This is the recommended way to do this: It will return HTTP status code 404 (which is good because it causes search engines to remove page from index) and it will display error.html in the browser.