Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different files by useragent in NGINX

How can I correctly write the configuration of the nginx server?

...
if the client has useragent (A) and it refers to http://somehost.domain/somefile.someextension
       nginx responding a file from the root /file.zip
if the client has useragent (B) and it refers to http://somehost.domain/somefile.someextension
       nginx responding a file from the root /file2.zip
if the client has useragent (C) and it refers to http://somehost.domain/somefile.someextension
       nginx responding 403 error
...

I did this code:

map $http_user_agent $browser {
        "~*Firefox"             "/var/www/test1";
        "~*Wget"                "/var/www/test2";
        "~*SomeUserAgent"       "/var/www/test3";
}

server {
...
root $browser

But how do I get the condition to pass to any address http://somehost.domain/somefile.someextension?

like image 215
Drello Avatar asked Nov 24 '25 12:11

Drello


1 Answers

You can use map, location and alias directives to map a specific URI to multiple files based on the value of a header.

For example (where all of the files are in the same directory):

map $http_user_agent $browser {
    default           "nonexistent";
    "~*Firefox"       "file.zip";
    "~*Wget"          "file1.zip";
}

server {
    ...
    location = /somefile.someextension {
        alias /path/to/directory/$browser;

        if (!-f $request_filename) {
            return 403;
        }
    }
}

The if block is only required to change the 404 response to a 403 response.

See this document for more.

like image 138
Richard Smith Avatar answered Nov 28 '25 15:11

Richard Smith