5

I try to set max-age header directive and Content-Disposition "attachment" as follows:

location / {

    # set up max-age header directive for certain file types for proper caching
    location ~* \.(?:css|js|ico|gif|jpe?g|png|mp3|mpeg|wav|x-ms-wmv|eot|svg|ttf|woff|woff2)$ {
        expires 7d;
        add_header Cache-Control "public";
    }

    # force download for ceratain file types
    location ~* \.(?:fb2|mobi|mp3)$ {
         add_header Content-Disposition "attachment";
    }
...
}

The problem is with the .mp3 files with match both location blocks. Only the first one is used (max-age). How can I have .mp3 with both - max-age and Content-Disposition "attachment"?

2 Answers 2

6

There's a good article about server and location block matching here. Only one location block can match, so you're going to create a location block just for mp3 files.

 location ~*  \.mp3$ {
   expires 7d;
   add_header Cache-Control "public";
   add_header Content-Disposition "attachment";
}

Nginx will match the first location block with the same prefix, so this needs to go before the two existing blocks, or you need to remove mp3 from the match criteria for the other two blocks.

4
  • OP stated "Only the first one is used... how can I have both...?" So not sure how your instructions on using Google or your short answer helps here? Jun 13, 2017 at 21:30
  • 1
    @BazzaDP good points, I've edited my answer to more directly answer the question.
    – Tim
    Jun 13, 2017 at 21:35
  • Much better @Tim! Jun 13, 2017 at 21:37
  • Is there a general solution? Assuming I have three or four or whatever types of location directives, is there another way than writing down all possible combinations?
    – Marian
    Aug 20, 2018 at 20:13
0

Given that only the first location is used, why not just do this?:

location / {

    # set up max-age header directive for certain file types for proper caching
    location ~* \.(?:css|js|ico|gif|jpe?g|png|mpeg|wav|x-ms-wmv|eot|svg|ttf|woff|woff2)$ {
        expires 7d;
        add_header Cache-Control "public";
    }

    # force download for ceratain file types
    location ~* \.(?:fb2|mobi)$ {
         add_header Content-Disposition "attachment";
    }

    # For mp3 files set both:
    location ~* \.mp3$ {
        expires 7d;
        add_header Cache-Control "public";
        add_header Content-Disposition "attachment";
    }

...
}

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.