简体   繁体   中英

Redirect to Apache built-in 404 page with mod_rewrite?

Is there a way to actively serve Apache's default, built-in 404 page for a number of URLs using mod_rewrite? Not a custom error document, but a rule like

RewriteCond %{REQUEST_URI} ^/dirname/pagename
RewriteRule -- serve 404 page -----

I know how to build a PHP page that sends the 404 header and have mod_rewrite redirect all the URLs there but I would prefer a solution that is based on mod_rewrite only.

I just had the idea of redirecting to a non-existent address:

RewriteCond %{REQUEST_URI} ^/dirname/pagename
RewriteRule .* /sflkadsölfkasdfölkasdflökasdf

but that would give the user the message "/sflkadsölfkasdfölkasdflökasdf does not exist" on the error page, which looks a bit unprofessional.

You can use the R flag on the RewriteRule to force a redirect with a given status code:

While this is typically used for redirects, any valid status code can be given here. If the status code is outside the redirect range (300-399), then the Substitution string is dropped and rewriting is stopped as if the L flag was used.

So this:

RewriteRule ^/?page\.html$ - [R=404]

would return the default 404 page for /page.html . Since this is a regexp, remember the escaping \\. and anchoring $ .

- is ignored (ie "the Substitution string is dropped"), but there still needs to be something there to keep the rule well-formed.

The best way to do that is to set the R flag with the status code 404:

RewriteCond %{REQUEST_URI} ^/dirname/pagename
RewriteRule ^ - [L,R=404]

But this is only available since Apache 2.

I confirm that

RewriteRule ^ - [L,R=404]

or

RewriteRule ^ - [L,redirect=404]

won't work. Here is the explanation from the official Apache website:

However, if a status code is outside the redirect range (300-399) then the substitution string is dropped entirely, and rewriting is stopped as if the L were used.

So the best solution is to redirect to a 404.php file with the 404 header as explained later.

This should work:

RewriteEngine on
RewriteRule ^/page.html /error404.html [L]

That won't give the 404 header though. You could try chaning to flag to [L,R=404] but I doubt that will work (it's supposed to be for redirects only).

Your idea of doing so in PHP would work. If all your "error pages" pages are server-side (ie PHP) then you could simply use this code:

<?php
header( 'HTTP/1.0 404 Not Found' );
include 'error404.html';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM