nginx - response based on the requested header
Asked Answered
S

2

5

I have nginx 1.0.8 installed. here is my problem: I have 2 files : file1.js and file2.js. the requested path is something like this:

www.mysite.com/files_dir/%user%/file.js

If the requested header : "X-Header" exists and has the value "OK" then the responded content should be file1.js else file2.js.

The files are situated in "html/files_dir" and %user% is a set of directories that represents the usernames registered through my service.

How do I configure this in nginx? I'm not interested in php, asp or similar technologies only if it's possible with nginx.

Thanks

Sackman answered 6/2, 2012 at 22:36 Comment(0)
D
10

map lets you define a variable's value based on another variable. map should be declared at http level (i.e. outside of server):

map $http_x_header $file_suffix {
  default "2";
  OK      "1";
};

Then the following location should do the trick using your new variable $file_suffix

location ~ ^(/files_dir/.+)\.js$ {
  root html;
  try_files $1$file_suffix.js =404;
}
Diaconicum answered 7/2, 2012 at 7:28 Comment(0)
M
1

You could do this with nginx very easily. This is example:

location /files_dir/ {

    set $file = file2.js;
    if ( $http_x_header = OK ) {
        set $file = file1.js;
    }
    rewrite ^(/files_dir/.*)/file.js$ $1/$file last;

}

You could read about HTTP variables in NGINX here , and about nginx rewrite module here

Modern answered 7/2, 2012 at 7:8 Comment(1)
thanks you're answer was also good but set $file = file2.js; is without "=".. just set $file file2.js;Sackman

© 2022 - 2024 — McMap. All rights reserved.