nginxreverse-proxyexpires-header

nginx Expires header and reverse proxy not working


I am trying to configure an Expires header for static files on nginx (0.7.67). The static files are served from a Golang reverse proxy:

location /rev/ {
  proxy_pass http://localhost:8910/;
  proxy_redirect off;
  proxy_set_header  Host               $host;
  proxy_set_header  X-Real-IP          $remote_addr;
  proxy_set_header  X-Forwarded-For    $proxy_add_x_forwarded_for;
  proxy_set_header  X-Forwarded-Proto  https;

  # I am putting this here, because nginx only uses one location. Is this OK?
  location ~* \.(js|css|jpg|jpeg|gif|png|svg|ico|pdf|html|htm)$ {
    expires 30d;
  }
}

When I do it this way there is no error restarting nginx, but the static files are not served anymore.

I already tried the following constellation, but it's not working:

server {
  ...
  location /rev/ {
    proxy_pass http://localhost:8910/;
    proxy_redirect off;
    proxy_set_header  Host               $host;
    proxy_set_header  X-Real-IP          $remote_addr;
    proxy_set_header  X-Forwarded-For    $proxy_add_x_forwarded_for;
    proxy_set_header  X-Forwarded-Proto  https;
  }

  location ~* \.(js|css|jpg|jpeg|gif|png|svg|ico|pdf|html|htm)$ {
      expires 30d;
  }
}

Question: How can I apply an expires header for static files which are located on an application behind a reverse proxy?


Solution

  • The only way i have managed to accomplish it was this way:

    location / {
        proxy_pass  http://tomcat;
    }
    
    # CACHING WITH NO LOGGING
    location ~* ^.+\.(atom|bmp|bz2|doc|docx|eot|exe|gif|gz|ico|jpeg|jpg|mid|midi|mp4|ogg|ogv|otf|pdf|png|ppt|pptx|rar|rss|rtf|svg|svgz|swf|tar|tgz|ttf|txt|wav|woff|xls|zip)$ {
        access_log  off;
        log_not_found   off;
        expires     max;
        proxy_pass  http://tomcat;
    }
    
    # CACHING WITH 404 LOGGING
    location ~* ^.+\.(css|js|xml)$ {
        access_log  off;
        log_not_found   on;
        expires     max;
        proxy_pass  http://tomcat;
    }
    

    Hope it helps!