I'm testing creating a cache in nginx and have it working great under both directories I have set up except the following: When I try to cache a php-generated image, it simply acts as a proxy to my apache server running the php image-generation script. It works fine on any static html, css, js, or text files. How can I get nginx to cache the php-generated images too? I'm thinking something might be missing from my PHP generation to make nginx think its a cacheable file, but not sure where to go from here.

Here is my nginx.conf:

user www-data;
worker_processes 4;
pid /var/run/nginx.pid;

events {
        worker_connections 768;
        # multi_accept on;

http {
  proxy_cache_path  /var/www/cache/muncherelli/cdn levels=1:2 keys_zone=muncherelli:8m max_size=1000m inactive=600m;
  proxy_cache_path  /var/www/cache/mi/client/images levels=1:2 keys_zone=miclient:8m max_size=1000m inactive=600m;
  proxy_temp_path /var/www/cache/tmp;

  server {
    location /muncherelli/cdn/ {
      proxy_pass http://muncherelli.com/wp-content/;
      proxy_cache muncherelli;
      proxy_cache_valid  200 302  60m;
      proxy_cache_valid  404      1m;

    location /mi/client/images/ {
      proxy_pass http://client.images.example.com/;
      proxy_cache miclient;
      proxy_cache_valid  200 302  60m;
      proxy_cache_valid  404      1m;


and the image creation part of my php script:

$img = imagecreatefromjpeg($full_image_path);

header('Content-Type: image/jpeg');

How do I get nginx to cache these images as well?

  • What are the full HTTP headers output from your PHP script to nginx? – Tero Kilkanen Jul 6 '15 at 13:06
  • @TeroKilkanen, looks like I goofed. Checked the header and found a stray Set-Cookie:·fileDownload=true;·path=/ in the header. Removed that and we are caching away! Feel free to answer the question looking into headers and I'll give you the point. Thank you! – muncherelli Jul 6 '15 at 13:16

Most likely some extra header is preventing nginx from caching the response.

  • 1
    Yes, that was the issue. I found a lingering set cookie in the HTTP headers. Thanks! – muncherelli Jul 10 '15 at 17:21

I had to add my answer too, I was debugging for 2 weeks (true unfortunately).

php pages (or others) that have setcookie() are NOT cached by default in nginx cache / reverse proxy.

I had a cookie "login_return_url" on each listing details pages (over 500 000) and I didn't understand why site seems slower and gets less and less traffic and google hits despite the caching that apparently worked fine.

And I was mostly logged in (no login return cookie needed) so I got cached pages while everyone else didn't.

Thank you @muncherelli !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.