Bypass cache if PHPSESSID exists

Christos Chatzaras chris at cretaforce.gr
Thu May 9 17:11:18 UTC 2024


Hello,

I want to bypass cache if PHPSESSID exists.

I have this configuration:

http {
	fastcgi_cache_path /tmpfs/cache levels=1:2 keys_zone=fastcgicache:10m inactive=10m max_size=1024m;
	fastcgi_cache_key $device_type$scheme$request_method$host$request_uri;
	fastcgi_cache_min_uses 1;
	fastcgi_cache fastcgicache;
	fastcgi_cache_valid 200 301 10s;
	fastcgi_cache_valid 302 1m;
	fastcgi_cache_valid 404 5m;
	fastcgi_cache_lock on;
	fastcgi_cache_lock_timeout 8000;
	fastcgi_pass_header Set-Cookie;
	fastcgi_pass_header Cookie;
	fastcgi_ignore_headers Cache-Control Expires Set-Cookie;
	fastcgi_no_cache $no_cache;
	fastcgi_cache_bypass $no_cache;
}

server {

	location ~ [^/]\.php(/|$) {

		set $no_cache "";
		
		if ($request_method = POST) {
			set $no_cache "1";
		}
		
		if ($http_cookie ~* "_mcnc|PHPSESSID") {
			set $no_cache "1";
		}
		
		if ($no_cache = "1") {
			add_header Set-Cookie "_mcnc=1; Max-Age=31536000; Path=/";
		}
	} 
}

When I repeatedly run curl, the content is fetched from the cache, and the Set-Cookie header always contains "PHPSESSID=604e406c1c7a6ae061bf6ce3806d5eee", leading to session leakage:

curl -I https://example.com
HTTP/1.1 200 OK
Server: nginx
Date: Thu, 09 May 2024 16:37:15 GMT
Content-Type: text/html; charset=UTF-8
Connection: keep-alive
Vary: Accept-Encoding
Set-Cookie: PHPSESSID=604e406c1c7a6ae061bf6ce3806d5eee; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate
Pragma: no-cache
X-Cache: HIT

Any idea what's wrong with my configuration?

Kind regards,
Christos Chatzaras


More information about the nginx mailing list