Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 754
Pekka Avatar asked Mar 15 '10 12:03

Pekka


People also ask

What is Apache mod_rewrite?

mod_rewrite is an Apache module that allows for server-side manipulation of requested URLs. mod_rewrite is an Apache module that allows for server-side manipulation of requested URLs. Incoming URLs are checked against a series of rules. The rules contain a regular expression to detect a particular pattern.

What is $1 in Apache rewrite rule?

The $1 is basically the captured contents of everything from the start and the end of the string. In other words, $1 = (. *) .


2 Answers

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 (i.e. "the Substitution string is dropped"), but there still needs to be something there to keep the rule well-formed.

like image 187
mercator Avatar answered Sep 28 '22 09:09

mercator


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.

like image 30
Gumbo Avatar answered Sep 28 '22 09:09

Gumbo