nginx location 指令不首先查找指定的文件

nginx location directive doesn't look for specified file first

我有一个简单的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 路径。

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

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 确实有效

当您给出目录的 URI 时,index 指令将附加文件名。

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

/foo URI 没有指向目录。如果目录 /var/www/example.com/foo/) 确实存在,index foo.html; 语句将导致 nginx 到 return 文件 /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