Nginx从子文件夹提供索引文件

时间:2020-02-26 12:32:02

标签: http nginx webserver http-status-code-301 httpserver

我想从根文件夹提供一个索引文件,并从根目录提供一个子文件夹。

我的nginx服务器配置如下:

server {

    listen       80;
    server_name  localhost;
    root /data/;
    index  index.html index.htm index.txt;

    location / {
    }

    location /a {
        alias   /data/a/;
    }

}

我的目录结构如下:

/data/:
a  index.txt

/data/a:
index.txt

如果随后执行curl localhost,则会得到文件/data/index.txt的内容。 但是curl /localhost/a给了我301curl localhost/a/index.txt有效。

为什么我不能使用curl /localhost/a访问index.txt?

我尝试在root块中使用alias而不是location /a,还尝试为位置index.txt指定/a,但没有成功。

我看到类似的帖子,例如 Nginx location configuration (subfolders) 但找不到答案。

1 个答案:

答案 0 :(得分:0)

index指令适用于以/结尾的URI:

因此URI /为您提供/index.txt的内容,而/a/为您提供`/a/index.txt的内容。

如果为Nginx提供目录的URI(但不带尾随/),则默认行为是重定向到相同的URI,但带尾随/

这就是index指令的工作方式。有关详细信息,请参见this document


如果您想要默认行为以外的其他东西,则必须使用try_files手动进行。有关详细信息,请参见this document

例如,要通过提供不带尾随index.txt的目录URI来返回/文件的内容,请使用:

root /data;

location / {
    try_files $uri $uri/index.txt =404;
}

请注意,在本示例或您所提问的示例中,location /a { ... }块都是不必要