nginx serve from different static directory based on user-agent

i have directory structure like this:

HTML
|
|--android/
|--ios/

In short i have 2 directory(ios & android) in HTML/

Both directory contains index.html . In android/index.html there is link to ../ios & In ios/index.html there is link to ../android for switching user from ios to android & android to ios..

server {
    listen 80 default_server;

    root /home/vishant/HTML;
    index index.html index.htm;

    server_name wishfeed.l;

    location / {
            try_files $uri $uri/ =404;
    }
}

my nginx configuration is like given above..

How to serve directory if user agent is ios / if user agent is android.


Solution 1:

The map directive can generate an appropriate document root from the user-agent string down.

For example:

map $http_user_agent $root {
    "~*android" /home/vishant/HTML/android;
    "~iPhone" /home/vishant/HTML/ios;
    default /home/vishant/HTML;
}

You will have to work on the regular expressions yourself, as I do not know if they are right for all cases.

The above map block is placed above the server block within the http context of the configuration file. In this case, it creates a variable called $root which may be used within the server block.


If you need to serve the entire site's content from either subdirectory, use $root to set the global root like this:

server {
    ...
    root $root;

    location / {
        ...
    }
}

If you only want the URI /index.html to be affected, use $root within a location. For example:

location = /index.html {
    root $root;
}