Score:1

add_header for certain request_uri

in flag

The app handles all the routing. So this basic configuration block works:

location / {
    try_files $uri $uri/ /index.html;
}

The issue is that I want to add a custom header whenever a visitor requests a certain URI. For example, /content. Well, that must be easy as:

location ~ ^/content {
   try_files $uri $uri/ /index.html;
   add_header X-CUSTOM-HEADER value;
}

But that doesn't work. Nginx is not creating that header. Then, I tried to remove the try_files directive from the content block but that doesn't work obviously as there's no "real" /content folder in the root directory. Thus, nginx will throw 404 not found error.

I also tried to move that block inside the root location block. Not working either.


In Apache, this can be done easily using this:

<If "%{THE_REQUEST} =~ pattern">
    Header set HEADER value;
</If>
Michael Hampton avatar
cz flag
Why do you use a regex in your `location`? It doesn't appear to be necessary.
Score:2
jp flag

You can set the header using a mapped variable. If the variable is set to an empty string, the header will be silently discarded.

For example:

map $request_uri $myheader {
    ~^/content   a_value;
}
server {
    ...
    add_header X-CUSTOM-HEADER $myheader;

    location / {
        try_files $uri $uri/ /index.html;
    }
}
Annahri avatar
in flag
Oh wow, didn't think about it. This works!!! I've spent hours finding out how to do this! Thanks!
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.