301 Redirects in PHP: Do I need to explicitly state that it is 301?

It 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/"); ?> 

I usually leave the first statement and just do ...

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

Could this second example be a 302 redirect?

+4
source share
1 answer

Yes.

To quote the exact manual :

The second special case is the "Location:" header. It not only sends this header back to the browser, but also returns the REDIRECT status code (302) to the browser if the status code 201 or 3xx is not already set.

The most likely reason for this is that a 302 Found is an unspecified destination redirect. There are four 3xx redirect headers you can use.

  • 301 Moved Permanently is a constant redirect, for example. for compatibility with old URLs. Thus, many browsers will cache the redirect location and will not be checked again.
  • 303 See Other - this is a redirect, for example, for the Post-Redirect-Get action - note that it is only defined as HTTP / 1.1
  • 307 Temporary Redirect means β€œyes, it's usually here, but right now, the resource is somewhere else” - this may not be the point you want: for example, you always want to redirect at this point. Again, defined in HTTP / 1.1
  • Finally, 302 Found is an unspecified destination redirection - for use if the above is not applicable, or when HTTP / 1.0 is desired for compatibility (is this still a problem in 2011?); as such, it is used by default.
+6
source

Source: https://habr.com/ru/post/1386472/


All Articles