Garrett Leyenaar
Garrett Leyenaar

Reputation: 81

301 Redirects in PHP: Do I need to explicitly tell it that it's a 301?

This one should be easy...

Do I need to explicitly tell PHP that I want to do a 301 redirect? Like this...

<?php
header("HTTP/1.1 301 Moved Permanently");
header("Location: http://www.example.com/");
?>

Usually, I leave off the first statement and just do...

<?php
header("Location: http://www.example.com/");
?>

Would that second example actually be a 302 redirect?

Upvotes: 4

Views: 545

Answers (1)

Piskvor left the building
Piskvor left the building

Reputation: 92752

Yes.

To quote the fine manual:

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.

The most likely reason for this is that a 302 Found is a nonspecified-purpose redirect. There are four 3xx redirect headers that you can use.

  • 301 Moved Permanently is a permanent redirect, e.g. for keeping compatibility with old URLs. As such, many browsers will cache the redirect location, and won't check again.
  • 303 See Other is the redirect intended e.g. for a Post-Redirect-Get action - note that it's only defined as of HTTP/1.1
  • 307 Temporary Redirect means "yeah, it's usually here, but right now, the resource is somewhere else" - that may not be the meaning you want: e.g. you always want to redirect at this point. Again, defined in HTTP/1.1
  • Finally, 302 Found is a unspecified-purpose redirect - to be used when the above aren't applicable, or when HTTP/1.0 compatibility is desired (is that still a concern in 2011?); as such, it is used as the default.

Upvotes: 6

Related Questions