【发布时间】:2013-09-10 10:25:23
【问题描述】:
我正在尝试使用 Nginx 将项目添加到现有网络服务器的子文件夹中。这是我的简单配置:
server {
listen 80 default_server;
server_name localhost;
root /var/www;
[...]
location = /my-project { return 301 /my-project/; }
location /my-project/ {
alias /var/www/my-project/web/;
index index.php;
location ~ /[^/]+/control(/|$) {
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/htpasswd;
if (-f $request_filename) { break; }
rewrite ^(.*)$ /my-project/index.php last;
}
if (-f $request_filename) { break; }
rewrite ^ /my-project/index.php last;
location ~ ^/[^/]+/index\.php$ {
include fastcgi_params;
fastcgi_pass unix:/var/run/fcgi.sock;
fastcgi_param SCRIPT_FILENAME $document_root/index.php;
}
}
}
因为/control 位置块内有一个重写指令,auth_basic 永远不会被触发,因为 Nginx 在身份验证之前执行重写。我应该以哪种方式修改配置,该身份验证是否有效?
PS:try_files 似乎不起作用,因为它从根 (/) 网络文件夹提供文件!?当我将if 替换为rewrite 并将rewrite 替换为try_files $uri /my-project/index.php?$query_string; 时,我得到一个404,因为Nginx 尝试提供文件/var/wwwindex.php(查看缺少的斜杠和根文件夹/var/www 而不是别名)。
编辑 18.09.2013: 正如 VBart 建议的那样,我现在正在使用以下配置来使身份验证正常工作
location ~ ^/(?<dir>my-project)(?<path>/.*)$ {
root /var/www/$dir/web;
location ~ ^/[^/]+/control(/|$) {
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/htpasswd;
try_files $path /$dir/index.php?$query_string;
}
try_files $path /$dir/index.php?$query_string;
location ~ ^/[^/]+/index\.php$ {
include fastcgi_params;
fastcgi_pass unix:/var/run/fcgi.sock;
fastcgi_param SCRIPT_FILENAME $document_root/index.php;
}
}
【问题讨论】: