PHP header( “Location: /404.php”, true, 404 ) does not work

后端 未结 5 1895
庸人自扰
庸人自扰 2021-01-04 09:04

I\'d like to use the following to redirect pages that are no longer present in the database to the custom 404 page:

ob_start();
....
if ( !$found ):
  header         


        
相关标签:
5条回答
  • 2021-01-04 09:37

    I've tried and make sure to check error_log file that is correct way is send 404 headers and then include error page to next line.

    <?php
    header('HTTP/1.1 404 Not Found');
    include 'search.php'; // or 404.php whatever you want...
    exit();
    ?>
    

    Finally you have to use exit() for text based browsers.

    0 讨论(0)
  • 2021-01-04 09:44

    You can't have an header 404 with a Location:

    You should display the error page and set a meta refresh with the new url if you want to redirect

    0 讨论(0)
  • 2021-01-04 09:50

    I know it's a old issue but I just found it handy:

    php set status header to 404 and add a refresh to correct page, like a 2 seconds after.

    header('HTTP/1.1 404 Not Found');
    header("Refresh:0; url=search.php");
    

    Then you have the 404 page showing up a few second before redirecting to fx search page.

    In my case, Symfony2, with a exception listener:

    $request  = $event->getRequest();
    $hostname = $request->getSchemeAndHttpHost();
    $response->setStatusCode(404);
    $response->setContent('<html>404, page not found</html>');
    $response->headers->set('Refresh', '2;url='.$hostname.'/#!/404');
    

    time ( 2) can be 0.2 if you wish very short time.

    0 讨论(0)
  • 2021-01-04 09:51

    Maybe without redirect?

    if ( !$found ):
       include('../404.php');
       exit();
    endif;
    
    0 讨论(0)
  • 2021-01-04 09:55

    I think your problem is because of the output buffering you're starting, or because you can't redirect with a 404. The first code example shows the output buffer starting but exiting instead of cleaning the output buffer and stopping output buffering.

    Change the first example to:

    if (!$found) {
      ob_end_clean();
      header('Location: /404.php');
      exit();
    }
    
    0 讨论(0)
提交回复
热议问题