How to add headers to only specific files with ngi

2019-03-15 07:36发布

问题:

I have pictures, and I want to add their headers to max, I have profile pictures which can be changed and post pictures, I want to add headers only for post pictures, but not to profile pictures, I have no idea how can I manage this. thank you, this is my configuration,

this is the path of posts, /post/name-of-the-picture.jpg

this is the path of users, /user/name-of-the-picture.jpg

I only want to add headers to post path

location ~* \.(css|js|png|gif)$ {
   expires max;
   add_header Pragma public;
   add_header Cache-Control "public";
}

回答1:

Currently we have two options to solve this:

Option 1:

Duplicated locations: NGINX looks for the best match. (a little better performance)

location /post/ {
    post config stuff;
    .
    .
    .
}    
location ~* ^/post/.*\.(css|js|png|gif)$ {
    post/files.(css|js|png|gif) config stuff;
    expires max;
    add_header Pragma public;
    add_header Cache-Control "public";
}
location /user/ {
    user folder config stuff;
    .
    .
    .
}    
location ~* ^/user/.*\.(css|js|png|gif)$ {
    user/files.(css|js|png|gif) config stuff;
    .
    .
    .
}

Option 2:

Nested locations: Filtered by extension in the inner location blocks

location /post/{
    ...

    location ~* \.(css|js|png|gif)$ {
        expires max;
        add_header Pragma public;
        add_header Cache-Control "public";
    }
}
location /user/{
    ...

    location ~* \.(css|js|png|gif)$ {
        ...

    }
}


标签: nginx header