未分类

解决 Nginx 报 directory index of "xxx" is forbidden 错误

Nginx 配置如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
server {
listen 8002;
root /workspace/php-research;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
include fastcgi_params;
}
}

请求 127.0.0.1:8002 报错:

1
2019/09/14 23:45:15 [error] 3597#0: *7 directory index of "/workspace/php-research/" is forbidden, client: 127.0.0.1, server: , request: "GET / HTTP/1.1", host: "127.0.0.1:8002"

Nginx 配置中有一段 try_files $uri $uri/,当我们访问 127.0.0.1:8002 的时候,Nginx 会去访问 root 指定的目录 /workspace/php-research,但是默认配置下列出目录文件是被关闭的,所以报错显示禁止访问 /workspace/php-research。

如果想要避免报错可以加上 autoindex on 配置,即允许目录浏览。

或者加上 index index.php 配置,修改 Nginx 会在 /workspace/php-research 目录中寻找 index.php 文件,并做内部跳转到 /index.php 这个地址。

修改后的配置如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
server {
listen 8002;
root /workspace/php-research;
index index.php;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
include fastcgi_params;
}
}