Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Redirect with status doesn't work

Hello !

I want to redirect to a login page if the user is not logged in (seems logic).

But when I try to add a status to the redirection, it doesn't work.

First try

I want to redirect in the beforeExecuteRoute. So I tried this (according to this thread) :

return $this->dispatcher->setReturnedValue($this->response->redirect("user/login", false, 401));

and this

$this->dispatcher->setReturnedValue($this->response->redirect("user/login", false, 401));
return false;

In both cases, Curl displays a 401 status (good), but the page stays to the current page and doesn't redirect to /user/login (bad)

Second try

$this->response->setStatusCode(401, "Unauthorized");
return $this->response->redirect("user/login");

Here, Curl displays a 302 status (bad), but the page redirect correctly to /user/login (good)

Third try

return $this->response->redirect("user/login", false, 401);

Here I got the same results as the first try...

So, how can I have a 401 redirect status with Curl and that my page redirect to /user/login too ?

Anyone has the same problem ?

By the way : I'm using Nginx and php-fpm, debian7, and I'm using phalcon 1.3.4 (no phalcon 2 for the moment).

PS : I apologize for my English.


You can't redirect with a 401 status header, 4** codes are not made for redirection, instead use a 3** header. Moreover in your case would be more appropriate send a non authorized header and then redirect with JavaScript.

    $this->response->setStatusCode('401', 'Unauthorized');

    $url = $this->url->get('user/login');

<!DOCTYPE html>
        <meta name=robots content=noindex>
        <meta http-equiv=refresh content="0;URL='{$url}'">
        setTimeout(function () {
        }, 1e3);

Hi !

Ok then, I will use 3XX redirect only. I thought it was possible...

I tried the redirect by javascript but it didn't work.

Thanks for your help !