views:

623

answers:

4

Please take a look at the following .htaccess

ErrorDocument 404 /404/

RewriteEngine On
RewriteRule (.*) index.php [L]

With this setup, I am using header('HTTP/1.1 404 Not Found'); in PHP to redirect to the error handling page and send the appropriate HTTP status code. The correct 404 status code is sent, but the browser shows a blank page and the access log shows "GET /invalid-url/ HTTP/1.1" 404 -

Can anyone tell me how to make ErrorDocument work with Apache URL rewrites?

A: 

It should work if you define the Rewrite before the ErrorDocument.

JonnyLitt
Well, it didn't. I think Benoit is right. Only sending a 404 header from PHP with no content, does not force Apache to serve the content at the URL defined in my ErrorDocument. I hoped for that, but it doesn't happen.
bogdanvursu
A: 

Try this


ErrorDocument 404 /404.html

RewriteEngine On
RewriteRule (.*) index.php [L]

Gaurav Sharma
Nope, that won't help at all. Plus, changing the URL would break some things in my app.
bogdanvursu
I changed nothing in the RewriteRule it is same as your posted one.I just edited your ErrorDocument line and it is correct for sure, see this link "http://httpd.apache.org/docs/2.0/mod/core.html#errordocument"
Gaurav Sharma
A: 

Yes declare 404 document after the Rewrite rules

It's normal your server do not push any 404 error, you're using a catchall regexp ((.*)) as the only rewrite rule.

But your issue is not really htaccess related. In php if you send 404 header the browser wont be redirected to the 404 page automaticaly, but you have to serve error page content yourself in PHP, as it is done by most frameworks with internal routing system.

Benoit
Hi Benoit,So you are saying that only sending a 404 header does not force Apache to server the content at the ErrorDocument URL.If I serve the content from PHP, after setting the 404 header, I do get the 404 page displayed in the browser, but the address bar still shows the invalid URL, instead of /404/.After giving some more thought, I guess that's not actually bad at all.
bogdanvursu
Hi, You're right, it does not seems bad if browser is not forwarded to real 404 page url. Apache does not redirect too using ErrorDocument declaration.IMHO it is better this way : search engines crawler will forget the url responding with 404 http response code, and humans will see a nice 404 page instead of apache's default one or worse, page with errors on it.
Benoit
A: 

I guess the answer to my question is: I don't need to. What I was trying to accomplish was a "404 redirect". That is, when requesting an invalid URL, redirect to the 404 document along with setting the "Status 404 Not found" header. And I am not sure that's something I want, because invalid URLs should be marked with the 404 status code, not redirected.

bogdanvursu