Nginx 尝试加载不存在的目录

Nginx tries to load non existent directory

当我输入 mydomain.com/randomfolder 或 domain.com/somefolder 时,它只会加载索引页

我的问题是有没有更好的方法来配置它以将用户重定向到错误页面,而不是仅仅尝试加载目录或处理请求?

server {
#listen 80 default_server;
#listen [::]:80 default_server ipv6only=on;
listen 443 ssl;

root /var/www;
autoindex on;
index index.html index.htm index.php;

server_name mydomain.com;

ssl_certificate    /etc/nginx/ssl/mydomain.com.crt;
ssl_certificate_key    /etc/nginx/ssl/mydomain.com.key;

location / {
    # First attempt to serve request as file, then
    # as directory, then fall back to displaying a 404.
    try_files $uri $uri/ /index.php;
    # Uncomment to enable naxsi on this location
    # include /etc/nginx/naxsi.rules
}

location /doc/ {
    alias /var/www/;
    autoindex on;
    allow 127.0.0.1;
    allow ::1;
    deny all;
}

location ~ \.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
    # With php5-cgi alone:
    #fastcgi_pass 127.0.0.1:9000;
    # With php5-fpm:
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_read_timeout 300;
    fastcgi_index index.php;
    include fastcgi.conf;
}

这是已发布配置的正常行为。

如果你想改变它,违规指令是:

 try_files $uri $uri/ /index.php;

而且,如果您的指令冒犯了您,请将其删除。

之所以令人反感,是因为它说要对每个 http 请求执行以下操作:

  1. 首先按原样尝试请求
  2. 然后尝试在末尾添加一个 /
  3. 最后,尝试获取 /index.php 而不是

你可以砍掉第三个项目,或者完全摆脱它。

您还可以添加一个custom 404 page:

error_page 404 /path/to/my/404.html ;

但你必须去掉 try_files 中的 /index.php,甚至整行,否则请求将失败,只有在失败时才会显示自定义 404。