【问题标题】:Nginx auth_basic and rewrite in subdirectory does not workNginx auth_basic 和子目录中的重写不起作用
【发布时间】: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;
    }
}

【问题讨论】:

    标签: nginx rewrite


    【解决方案1】:

    用途:

    error_page 404 =200 /my-project/index.php;
    

    而不是丑陋的重写:

    if (-f $request_filename) { break; }
    rewrite ^(.*)$ /my-project/index.php last;
    

    参考:

    附: try_files 不适用于 alias,因为错误:http://trac.nginx.org/nginx/ticket/97,但您可以将 alias 替换为 root 指令:http://nginx.org/r/root

    【讨论】:

    • 而且你不需要声明它两次,因为它是继承的。您可以在外部location 块中配置一次error_page
    • 请再次提供帮助,我可以看到,再也没有 POST 了? (所以没有登录表单,没有注册表单......正在工作)我认为error_page 不能处理 POST 请求。所以这不符合我的要求:(
    • 然后使用try_filesroot 指令代替alias
    • try_filesroot 一起使用会导致静态文件出现404。调试日志给出http uri: "/my-project/js/main.js" 并在trying to use file: "/my-project/js/main.js" "/var/www/my-project/web/my-project/js/main.js" 上失败,因为Nginx 使用完整的URI 在目录.../web 中查找文件,而不仅仅是/js/main.js
    • 在这种情况下,您应该修改您的 location 以仅捕获部分 URI,如下所示:location ~^/my-project(?&lt;path&gt;/.*)$ { try_files $path /my-project/index.php?$query_string; }
    猜你喜欢
    • 1970-01-01
    • 2017-10-27
    • 2011-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-17
    • 1970-01-01
    相关资源
    最近更新 更多