Nginx setting expires header with proxy

12,308

Solution 1

location /assets/ {
    expires 30d;
    add_header Pragma public;
    add_header Cache-Control "public";

    proxy_pass http://localhost:2368/assets/;
    # or proxy_pass http://localhost:2368;
    proxy_set_header Host $host;
    proxy_buffering off;
}

Nginx doc for proxy_pass say that:

If the proxy_pass directive is specified with a URI, then when a request is passed to the server, the part of a normalized request URI matching the location is replaced by a URI specified in the directive.

I your case /assets/ get replaced by / (which is an URI). To avoid that either use proxy_pass with URI equal to location prefix (proxy_pass http://localhost:2368/assets/;) or don't use URI at all (proxy_pass http://localhost:2368;). But in latter case nginx will proxy unnormalized URI.

Solution 2

Managed to solve it by using the script below (note the /assets/ after the proxy).

server {
    listen 80;                                                             
    server_name xaviertalpe.be;

    client_max_body_size 10M;

    location /assets/ {
        expires 30d;
        add_header Pragma public;
        add_header Cache-Control "public";

        proxy_pass http://localhost:2368/assets/;
        proxy_set_header Host $host;
        proxy_buffering off;
    }

    location / {
        proxy_pass http://localhost:2368/;
        proxy_set_header Host $host;
        proxy_buffering off;
    }
}
Share:
12,308
xaviert
Author by

xaviert

Software architect and tech lead living in Belgium.

Updated on June 27, 2022

Comments

  • xaviert
    xaviert almost 2 years

    I have the following base Nginx configuration (pre-installed Ghost platform on DigitalOcean droplet):

    server {
        listen 80;                                                             
        server_name xxx.com;
    
        client_max_body_size 10M;
    
        location / {
            proxy_pass http://localhost:2368/;
            proxy_set_header Host $host;
            proxy_buffering off;
        }
    }
    

    Now I tried to set the following expiry header for my assets but without success:

    location ~ ^/assets/ {
        expires 30d;
        add_header Pragma public;
        add_header Cache-Control "public";
    }
    

    Based on the information I've found, Nginx only uses one location path at a time so have to copy the proxy_* parameters inside the assets location block. If I just copy them I get an error (regex with proxy_pass) that can be solved by rewriting the URL before passing it to the proxy. I already did some experiments with that but I don't get it to work either.

    Does anyone have an example of how to set expiry headers when a proxy_pass is present? I simply want all files under xxx.com/assets/ to have the proper expiry date.

  • xaviert
    xaviert over 9 years
    Thanks for confirming the answer. This way I know my own solution (posted below) was correct :).