【问题标题】:nginx location directive doesn't look for specified file firstnginx 位置指令不会首先查找指定的文件
【发布时间】:2019-01-20 16:54:23
【问题描述】:

我有一个简单的 nginx 配置文件 -

server {
    listen 80 default_server;

    root /var/www/example.com;

    #
    # Routing
    #

    location / { index index.html; }
    location /foo { index foo.html }

    #
    # Logging
    #

    access_log /var/log/nginx/{{ www_domain }}.log;
    error_log  /var/log/nginx/{{ www_domain }}-error.log error;

    server_name example.com;
    charset utf-8;
}

如您所见,只有 2 条路径 - / 和 /foo 路径。

  • 当我转到www.example.com/ 时,一切正常。我可以看到 index.html 页面正在提供服务。

  • 当我转到 www.example.com/foo 时,当我应该访问 foo.html 页面时,我收到了 404 错误。

查看日志,我看到了这个错误:

2018/08/13 21:51:42 [error] 14594#14594: *6 open() "/var/www/example.com/foo" failed (2: No such file or directory), client: XX.XX.XX.XX, server: example.com, request: "GET /foo HTTP/1.1", host: "example.com"

该错误意味着它正在寻找一个名为 /var/www/example.com/foo 的文件,而不是像我预期的那样 /var/www/example.com/foo.html。

为什么一般会发生这种情况,特别是为什么它不会发生在我的根路径/ 上?

谢谢!

编辑:如果我直接访问www.example.com/foo.html,它确实有效

【问题讨论】:

    标签: nginx nginx-location


    【解决方案1】:

    index 指令将在您提供目录的 URI 时附加文件名。

    所以/指向根目录(/var/www/example.com/),index index.html;语句导致nginx返回文件/var/www/example.com/index.html。

    /foo URI 未指向目录。如果目录/var/www/example.com/foo/) 确实存在,index foo.html; 语句将导致nginx 返回文件/var/www/example.com/foo/foo.html。哪个不是/var/www/example.com/foo.html。

    您试图实现的是某种无扩展方案,这与 index 指令无关。

    有关index 指令的详细信息,请参阅this document。


    有许多可行的解决方案,例如,使用try_files 而不是index:

    location /foo { try_files /foo.html =404; }
    

    详情请见this document。

    【讨论】:

    • 谢谢!这完全有道理 - 看起来我对 index 指令的工作方式有一个根本的误解。
    猜你喜欢
    • 2012-11-09
    • 1970-01-01
    • 1970-01-01
    • 2018-11-05
    • 2012-04-22
    • 2020-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多