在 nginx 中使用别名作为相对 URL 时的禁止位置

Forbidden location when using alias in nginx for relative urls

我正在尝试在相关 URL 上使用 Nginx 设置 roundcube / phpldapadmin / ...,例如:

example.com/roundcube
example.com/phpldapadmin

源位于以下文件夹中:

/var/www/roundcube
/usr/share/phpldapadmin

Apache 2.4 一切正常,但我是 Nginx 的新手。我有以下 location for roundcube:

location /roundcube/ {
    root /var/www;
    index index.php;

    location ~ \.php$ {
        try_files $uri =404;
        include /etc/nginx/fastcgi_params;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}

效果很好,但 phpldapadmin 的以下内容不起作用:

location /phpldapadmin/ {
    alias  /usr/share/phpldapadmin/htdocs;
    index  index.php index.html index.htm;

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        include /etc/nginx/fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}

我得到一个 403 forbidden,其中包含以下日志:

2016/02/07 21:43:33 [error] 23047#0: *1 directory index of "/usr/share/phpldapadmin/htdocs" is forbidden, client: xxx.xxx.xxx.xxx, server: , request: "GET /phpldapadmin/ HTTP/1.1", host: ""

我检查了权限:

$ namei -om /usr/share/phpldapadmin/htdocs
f: /usr/share/phpldapadmin/htdocs
 drwxr-xr-x root root     /
 drwxr-xr-x root root     usr
 drwxr-xr-x root root     share
 drwxr-xr-x root root     phpldapadmin
 drwxr-xr-x root www-data htdocs
$ ls -l /usr/share/phpldapadmin/htdocs/index.php
-rw-r--r-- 1 root root 20036 Oct 28 17:32 /usr/share/phpldapadmin/htdocs/index.php

我尝试将所有者更改为 :www-data,但没有成功。当我为 roundcube 尝试以下操作时,它不起作用:

location /roundcube/ {
    alias /var/www/roundcube;
    ...
}

我认为这可能是尾随 / 或类似问题的问题,但我对 nginx 很陌生,所以我找不到它...

基本上,我的逆问题是:

locationalias 都应该有一个尾随 / 或者都没有尾随 /。但在您的情况下,您应该对两个位置块使用 root 而不是 alias

location /roundcube {
    root /var/www;
    index index.php;

    location ~ \.php$ {
        try_files $uri =404;

        fastcgi_pass unix:/var/run/php5-fpm.sock;

        include /etc/nginx/fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}

location /phpmyadmin {
    root  /usr/share;
    index  index.php index.html index.htm;

    location ~ \.php$ {
        try_files $uri =404;

        fastcgi_pass unix:/var/run/php5-fpm.sock;

        include /etc/nginx/fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}

fastcgi_index 不会在仅匹配 .php 的位置执行任何操作(参见 this document)。

两个块都需要 SCRIPT_FILENAME 参数(或者如果它已经在 /etc/nginx/fastcgi_params 中则不需要)。

或者你可以尝试写在 nginx.conf >> user username

的顶部

由于我使用的是 AWS Linux 我编写的 EC2 实例

user ec2-user;

而不是

user nginx;

这通过提供所有必需的权限解决了问题