PHP 410 redirect

19.3k views Asked by At

I'm using WordPress and I would to redirect all unauthorized users to the homepage.

In order to do so in the header file I put (at the begin of the file) the following PHP code:

if (bp_current_component() != "" 
    && bp_current_component() != "event" 
    && !is_user_logged_in() 
    && !isset($_COOKIE[affiplus]) 
    && !isset($_GET[affid]))
{
    header( "HTTP/1.1 410 Gone" ); 
    header( "Location: ".get_option('siteurl')."/home/");
}

Unfortunately the HTTP error code returned is always 302 (Moved permanently) and not 410 as I want. Why?

3

There are 3 answers

2
robjmills On BEST ANSWER

You can only send one response status code. So you can either send an error response (4xx) or a redirection response (3xx). Sending a 410 header when an unauthorised user tries to access a resource would be incorrect anyway.

I think just performing a 302 is more than adequate.

1
Leonid Shevtsov On

How about

header( "Location: ".get_option('siteurl')."/home/", true, 410);

The docs provide an in-depth explanation.

4
Lawrence Cherone On

Alternately you could use the refresh header this way it will still show a 410 response but also redirect.

<?php 
if (bp_current_component() != "" && 
    bp_current_component() != "event" && 
    !is_user_logged_in() && 
    !isset($_COOKIE['affiplus']) && 
    !isset($_GET['affid']))
{
    header($_SERVER["SERVER_PROTOCOL"]." 410 Gone"); 
    header("Refresh: 0; url=".get_option('siteurl')."/home/");
    exit;
}
?>

The main reasoning for sending a 410 (Gone) or (Was a page but now its Gone) would be that search engines dont index the page.