V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
NGINX
NGINX Trac
3rd Party Modules
Security Advisories
CHANGES
OpenResty
ngx_lua
Tengine
在线学习资源
NGINX 开发从入门到精通
NGINX Modules
ngx_echo
j0hnj
V2EX  ›  NGINX

nginx 的 location 与 index 指令的问题

  •  
  •   j0hnj · 2018-05-07 00:00:50 +08:00 · 4183 次点击
    这是一个创建于 2179 天前的主题,其中的信息可能已经有所发展或是发生改变。

    按照 nginx 文档 中对 index 指令的说法:

    It should be noted that using an index file causes an internal redirect, and the request can be processed in a different location. For example, with the following configuration:
    
    location = / {
        index index.html;
    }
    
    location / {
        ...
    }
    a “/” request will actually be processed in the second location as “/index.html ”.
    

    在匹配了一个 location 块后,如果这个块有或者继承了 index 指令,就会触发一次内部重定向,也就是重新开始一次 location search, 然后匹配到了第二个 location block.

    但是在我的配置中:

    server {
        listen 80;
        server_name ubuntu;
    
        location = / {
            index index.html;
            return 200 '/exact';
        }
    
        location / {
             return 200 '/';
        }
    }
    

    使用 curl 请求得到的结果都是 /exact :

    # curl http://ubuntu
    /exact
    
    # curl http://ubuntu/
    /exact
    

    也就是说,实际匹配的确实第一个 location block, 请问这是为什么呢?

    4 条回复    2018-05-07 12:22:10 +08:00
    Arnie97
        1
    Arnie97  
       2018-05-07 01:08:16 +08:00 via Android
    你写的和文档里完全是两码事啊,文档里哪有 return 200 '/exact'; 这句话。
    你已经返回 200 了,响应就算完事了,自然不会再去找 index.html 在哪
    Arnie97
        2
    Arnie97  
       2018-05-07 01:13:04 +08:00 via Android   ❤️ 1
    文档里的意思并非不匹配第一个 block,而是先匹配了第一个 block 以后得到了结果 /index.html,而该结果又符合第二个 block 的规则
    j0hnj
        3
    j0hnj  
    OP
       2018-05-07 01:45:33 +08:00
    @Arnie97 明白了,感谢!用 return 主要是为看看到底用了哪个 block, 换成 add_header 后发现的确用的是第二个 block.
    Lax
        4
    Lax  
       2018-05-07 12:22:10 +08:00 via iPhone   ❤️ 1
    return 发生在 rewrite 阶段,早于 index 所在的 content 阶段。用 return 来测试修改了原来单纯用 index 的业务逻辑。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5346 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 07:34 · PVG 15:34 · LAX 00:34 · JFK 03:34
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.