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 · May 7, 2018 · 4761 views
    This topic created in 2958 days ago, the information mentioned may be changed or developed.

    按照 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 replies    2018-05-07 12:22:10 +08:00
    Arnie97
        1
    Arnie97  
       May 7, 2018 via Android
    你写的和文档里完全是两码事啊,文档里哪有 return 200 '/exact'; 这句话。
    你已经返回 200 了,响应就算完事了,自然不会再去找 index.html 在哪
    Arnie97
        2
    Arnie97  
       May 7, 2018 via Android   ❤️ 1
    文档里的意思并非不匹配第一个 block,而是先匹配了第一个 block 以后得到了结果 /index.html,而该结果又符合第二个 block 的规则
    j0hnj
        3
    j0hnj  
    OP
       May 7, 2018
    @Arnie97 明白了,感谢!用 return 主要是为看看到底用了哪个 block, 换成 add_header 后发现的确用的是第二个 block.
    Lax
        4
    Lax  
       May 7, 2018 via iPhone   ❤️ 1
    return 发生在 rewrite 阶段,早于 index 所在的 content 阶段。用 return 来测试修改了原来单纯用 index 的业务逻辑。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   973 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 22:03 · PVG 06:03 · LAX 15:03 · JFK 18:03
    ♥ Do have faith in what you're doing.