我的目标是通过与用于我的网站桌面版的通用 URL 不同的 URL(特定位置)来处理来自移动设备的请求。

我还需要从不同的文档根目录提供文件,该文档根目录应该被视为基本路径(我不希望我的位置成为目录结构的一部分)。

我有这个配置(摘录):

    location / {
        if ($http_user_agent ~* '(iPhone|iPod|iPad|Android|BlackBerry|webOS|Windows Phone)') {
            rewrite ^ /mobile/ permanent;
        }
        index  index.html index.htm;
    } 

    location /mobile/ {
        root /my/mobile/website;            # new document root
        rewrite ^/mobile(.*)$ $1 break;     # strip /mobile prefix from the path
#        try_files $uri $uri/ /index.html;  # I tried this (don't know exactly what this should do), but it doesn't work anyway
        index  index.html index.htm;
    }

这不起作用并导致重定向循环。

看起来,到 的请求www.mydomain.com/mobile/与来自 部分不匹配location /mobile/,但仍然属于location /,从而导致 301 重定向循环。

如果我保留该rewrite ^/mobile(.*)$ $1 break;指令,它就会起作用,我会得到一个放入/my/mobile/website/mobile目录中进行测试的 index.html 页面,但这不是应该从那里提供我的文件的地方。

我错过了什么?


最佳答案
1

我猜想问题是index

  • 原始网址为/mobile/
  • rewrite...breakURL 更改为/但仍保留在同一个location块内以继续处理请求。
  • index指令将 URL 更改为/index.html然后搜索匹配项location并将其移动到另一个location块,从而导致重定向循环。

您可以考虑使用alias来替换rootrewrite...break

例如:

location /mobile/ {
    alias /my/mobile/website/;
    index  index.html index.htm;
}

请注意,为了正确执行别名操作, locationandalias语句应该都以 结尾/,或者都不以 结尾/

2

  • 我不知道该index指令会触发像重定向这样的新搜索,这确实解释了正在发生的事情。我已经尝试过alias,但没有包括尾部斜杠……现在它起作用了!谢谢。


    – 

  • 1
    @Bozzy … It should be noted that using an index file causes an internal redirect 🙂


    –