对于空目录,nginx 404而不是403

我有我的nginx服务器的以下configuration:

server { listen 80 default_server; server_name example.com www.example.com; root /var/www/example.com/web; index index.php index.html; location / { # try to serve file directly, fallback to rewrite try_files $uri $uri/ @rewriteapp; } location @rewriteapp { # rewrite all to index.php rewrite ^(.*)$ /index.php last; } location ~ \.php$ { fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_split_path_info ^(.+\.php)(/.*)$; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param HTTPS off; fastcgi_buffer_size 128k; fastcgi_buffers 4 256k; fastcgi_busy_buffers_size 256k; } } 

和以下目录结构:

/var/www/example.com/:

  1. 的index.php
  2. /dir/index.html
  3. /空/

当客户端点击:“ example.com/dir/ ”时, index.html被提供。

当客户点击这样一个不存在的URL时:' example.com/non-existent/ ',那么index.php会在根目录中被提供。

但是,当客户端点击“ example.com/empty/ ”时,会发送403个状态码。

  1. 为什么它404发送时更合适,因为索引文件丢失在这个目录?
  2. 如何将这些请求映射到index.php (@rewriteapp)?

  1. 发生这种情况的原因是,在大多数Web服务器中,文件夹的默认操作是“目录列表”,默认情况下是禁用的。 如果您禁用目录索引,通常也会发生在Apache中。 你可以在nginx中做的是在你的try_files指令的结尾加上= 404。

  2. 你可以通过把/index.php放在try_files指令的最后来完成。 但是,由于安全原因,这并不总是值得推荐的。

另外,在你的configuration中对nginx有一个小小的误解:你应该用$ uri / index.php或者$ uri / index.html或者其他的replace$ uri /。 它停在try_files $ uri /因为它确实find了那个位置,但是用户被禁止访问它。

如果你想让nginx发送一个404,否则它会发送一个403,这是用error_page完成的:

 server { root /var/www/example.com/web; error_page 404 /s/404.html; error_page 403 =404 /s/404.html; location /s/404.html { internal; } # etc } 

location线使得http://example.com/s/404.html产生了404。