nginx 基于用户代理从不同的静态目录提供服务

vis*_*ant 5 nginx

我有这样的目录结构:

HTML
|
|--android/
|--ios/
Run Code Online (Sandbox Code Playgroud)

简而言之,我在 HTML/ 中有 2 个目录(ios 和 android)

两个目录都包含 index.html 。在 android/index.html 中有指向../ios 的链接,在 ios/index.html 中有指向../android 的链接,用于将用户从 ios 切换到 android & android 到 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我的 nginx 配置就像上面给出的一样..

如果用户代理是 ios / 如果用户代理是 android,如何提供目录。

Ric*_*ith 6

map指令可以从user-agent字符串向下生成适当的文档根。

例如:

map $http_user_agent $root {
    "~*android" /home/vishant/HTML/android;
    "~iPhone" /home/vishant/HTML/ios;
    default /home/vishant/HTML;
}
Run Code Online (Sandbox Code Playgroud)

您将不得不自己处理正则表达式,因为我不知道它们是否适用于所有情况。

上述map块放置在配置文件上下文中的server块上方http。在这种情况下,它会创建一个$root可以在server块中使用的变量。


如果您需要从任一子目录提供整个站点的内容,请使用如下$root设置全局root

server {
    ...
    root $root;

    location / {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您只想/index.html影响URI ,请$root在位置内使用。例如:

location = /index.html {
    root $root;
}
Run Code Online (Sandbox Code Playgroud)