Konstantin Bodnia
Konstantin Bodnia

Reputation: 1513

Nginx How to apply headers to a specific file without breaking the other rules

I have an nginx setup with several folders with aliases

        location /some-path {
            alias ../../path/to/folder1/www;
        }
        location /some-path-2 {
            alias ../../path/to/folder2/www;
        }

Every folder has one specific file that I'd like to be served with a header.

But when I try to add a rule for that file, the other rules stop working. This part I took from several answers here on stackoverflow:

        location ~* .*file.name$ {
            add_header 'Header' 'value';
        }

Then requesting /some-path/file.name and /some-path-2/file.name results in 404

How should I configure nginx to add these header rules and then fall back to the other rules?

Upvotes: 1

Views: 2056

Answers (1)

CheshirskyCode
CheshirskyCode

Reputation: 104

There are several variants of how to solve this issue. But each of them related to copy-paste a part of the configuration.

First variant

You may define separate location for each path

location ~ /some-path/file.name {
    alias ../../path/to/folder1/www;
    add_header 'Header' 'value';
}

location ~ /some-path-2/file.name {
    alias ../../path/to/folder2/www;
    add_header 'Header' 'value';
}

It would work because locations with regular expressions would be processed first.

Second variant

You may use nested locations

location /some-path {
    alias ../../path/to/folder1/www;
    location ~ file.name$ {
        add_header 'Header' 'value';
    }
}
location /some-path-2 {
    alias ../../path/to/folder2/www;
    location ~ file.name$ {
        add_header 'Header' 'value';
    }
}

Third variant

map $uri $path_alias {
    default "";
    ~/some-path "../../path/to/folder1/www";
    ~/some-path-2 "../../path/to/folder2/www";
}
server {
    location ~ ^some-path {
        alias  $path_alias;
        location ~ file.name$ {
            add_header 'Header' 'value';
        }
    }
}

Upvotes: 3

Related Questions