I want to add a cookie with a value once the user was logged in Symfony, a cookie that was saved during all requests for the current session and check if that cookie exists in nginx, if so the file will be shown.
The cookie was created and sent but it is valid only for one request and it is not sent along all new requests. I am adding new cookie in this way:
$response = new Response();
$time = time() + (3600 * 24 * 7);
$response->headers->setCookie(new Cookie("nametest", "test", $time, "/"));
$response->sendHeaders();
EDIT: Adding path as "/" sends the cookie across all requests. Now the last step is to verify the cookie in nginx. I am using the following nginx config:
location /assets/users/images/ {
if ($cookie_nametest !~* "test") {
return 301 https://example_domain.com/login;
}
}
One of the possible reasons for this can be that you didn't specify your cookie path. For example, if this cookie is being set on the login page https://example.com/login
, it will be sent from user browser to server for URIs starting with /login
and not any else. Here is an example of this behavior (initially the needed cookie was set with /referral
path and was invisible from the root URI, read both answer and comments). Following this example looks like you should use something like
$response->headers->setCookie(new Cookie("name_test", "test", $time, "/"));
However disadvantage of this approach is that your "secret" cookie name and value are hard-coded within the nginx config. Since your original question title was How to block direct file access for non authenticated users? I can suggest you a completely different solution using the X-Accel-Redirect
response header. The idea is that you can check if the user is logged in at the backend and then respond with the right path to the protected file. Here is the official documentation and here is an example. Note the internal
keyword inside the protected location
block.