Nginx 403 error: directory index of [folder] is forbidden

1,374 阅读1分钟

问题描述:

使用如下的try_files配置,想要实现的效果是输入localhost:8000,直接跳转到localhost:8000/xx/index.html

server {
        listen 8000;
        location / {
            root project;
            index index.html index.htm;
            try_files $uri $uri/ /xx/index.html;
        }
    }

但浏览器输入localhost:8000,返回403 Forbidden

问题原因及解决

因为 nginx 会尝试索引目录,并被自身阻止。

try_files $uri $uri/ 表示从根目录尝试 uri 指向的文件,如果该文件不存在,则尝试使用目录(因此是 /)。当 nginx 访问一个目录时,它会尝试对其进行索引并将其中的文件列表返回给浏览器 / 客户端,但是默认情况下目录索引是禁用的,因此它会返回错误 “Nginx 403 错误:[文件夹] 的目录索引” 是禁止的”。

解决办法:去除$uri/

try_files $uri /xx/index.html;