Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't seem to send 404 and Location headers together

I am trying to send both when a database result is empty (it's a product page).

My code I am using now, which works:

    header("Status: 404 Not Found");
    include_once("404.html");
    exit;

The code that I tried initially that did not work:

    header("Status: 404 Not Found");
    header("Location: 404.html");
    exit;

With the latter code, I could use either, but not both. In other words, I could send the 404 header and see it show up in Wireshark, OR I could send the Location header and redirect, but if i tried to send both, only the 404 would get sent and the Location header would nor redirect.

I have solved problem with a workable solution, but I would like to know why this is happening.

PHP 5.2 on Linux with FastCGI.

Thanks.

like image 595
Jazzy Avatar asked May 05 '12 22:05

Jazzy


2 Answers

You can't send both because they're mutually exclusive.

According to the docs for header():

The second special case is the "Location:" header. Not only does it send this header back to the browser, but it also returns a REDIRECT (302) status code to the browser unless the 201 or a 3xx status code has already been set.

So sending both would be nonsense. You'd be saying, to the browser, "That document does not exist. Also, the document was moved to the following location". Those are contradictory.

The solution you found is not "a workaround" -- it's the Right Way To Do It™

like image 67
timdev Avatar answered Sep 30 '22 04:09

timdev


The latter code doesn't work because 404.html actually exists on the server. You're sending a 404 status code then redirecting to an existing page, resulting in a 200 (Found) status code.

like image 42
Herbert Avatar answered Sep 30 '22 04:09

Herbert