Home Cant redirect using php's header function
Reply: 3

Cant redirect using php's header function

nikksan Published in 2018-01-10 10:05:22Z

I am having a very strange issue. I am doing bunch of redirects on a website and want to redirect '/old_url' and '/old_url.html' to '/new_url'. Everyting works fine with '/old_url', however the '/old_url.html' always returns 404. After inspecticting the response header, I can see my redirect listed there, but it simply doesnt redirect. Here is my code

 if($query && !headers_sent()){
        header('Location: ' . $query[0]['new_url'], true, (int)$query[0]['status_code']);

And here are the response headers from the browser.

As you can see there is a location header. Anyone knows why it is not working?

Philipp Wrann
Philipp Wrann Reply to 2018-01-10 10:10:52Z

I think a browser will not follow a Location header, if the HTTP status is 404. Send a 301 Status code with your response and you should be fine

Your response should look like:

HTTP/1.1 301 Moved Permanently
Location: {URL}

Also i would recommend to send redirect to an absolute url


Have a look at this: http://php.net/http-response-code

Alive to Die
Alive to Die Reply to 2018-01-10 11:34:57Z

/old_url, is a path which will result in reading the index.php / index.htm.

/old_url.html is a file, which tries to read the file itself, not any PHP script.

You might want to use something like htaccess for redirecting.

nikksan Reply to 2018-01-10 11:13:45Z

Weird.. This code is not working.

 header('Location: ' . $query[0]['new_url'], true, (int)$query[0]['status_code']);

But this one works.

    case 301:
     header("HTTP/1.1 301 Moved Permanently"); 
     header("Location: " . $query[0]['new_url']);
    case 302:
      header("HTTP/1.1 302 Moved Temporarily"); 
      header("Location: " . $query[0]['new_url']);
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.313362 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO