Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jjgg's avatar
Level 1

Laravel with nginx auth_request - caching Laravel response

I use a Laravel application that is the front end to some mapping software. I currently have it configured and working as so:

        location /m/ {
                auth_request /m/auth;
                proxy_pass http://mapservice.local/
        }

        location = /m/auth {
                internal;

                proxy_pass http://laravel.local/auth;

                proxy_pass_request_body off;
                proxy_set_header Content-Length "";
        }

When the browser makes requests to /m/, nginx calls the /m/auth location, which is protected by the sanctum middlewhere, and is authenticated appropriate.

The challenge is there are 1000s of these calls because it's mapping tiles. This service isn't under much load but it's not that efficient to spin up Laravel for each request.

To cache I have tried the following:

proxy_cache_path /usr/local/nginx/cache/auth levels=1:2 keys_zone=auth_cache:10m max_size=128m inactive=10m use_temp_path=off;
        location = /m/auth {
                internal;

                proxy_cache             auth_cache;
                proxy_cache_methods     GET HEAD POST;
                proxy_cache_key         $cookie_laravel_session; 
                proxy_cache_valid       401 30m;
                proxy_cache_valid       200 5m;

                proxy_pass http://laravel.local/auth;

                proxy_pass_request_body off;
                proxy_set_header Content-Length "";
        }

The cookie "laravel_session" exists, however no cache is ever created. Does anyone have experience with this? I found this stackexchange - but it hasn't given me that many additional pointers.

0 likes
1 reply
jjgg's avatar
jjgg
OP
Best Answer
Level 1

Thankfully, I haven't been working on this for a year :) But I finally had a spare gap to do a deep dive on this and have found that nginx doesn't cache responses that include the Set-Cookie header. Given Laravel authentication pipelines include Set-Cookie on every response you need to tell nginx to ignore those headers, your auth block needs to look something like this:

    location = /m/auth {
        internal;

        proxy_pass http://laravel.local/auth;

        proxy_pass_request_body off;
        proxy_set_header Content-Length "";
        proxy_set_header X-Original-URI $request_uri;

        proxy_ignore_headers Set-Cookie; #this here

        proxy_cache auth_cache;
        proxy_cache_methods GET;
        proxy_cache_valid 200 10m;
        proxy_cache_key "$cookie_session";
    }
1 like

Please or to participate in this conversation.