密码保护.htaccess中的特定漂亮URL



>我需要通过.htpasswd密码保护.htaccess中的许多漂亮的URL。但是我希望许多受保护的漂亮URL中的每一个都有不同的用户/登录名(以及未专门保护的页面的一般登录名)。

因此,例如,我想保护:

使用特定用户/密码:

http://www.example.com/pretty/url

使用其他用户/密码:

http://www.example.com/pretty/link
使用通用用户/密码

(所有其他用户/密码)

http://www.example.com/pretty/generic
http://www.example.com/pretty/all
http://www.example.com/pretty/

试图使用这个答案中的代码,我发现它最适合我的需求:

# Do the regex check against the URI here, if match, set the "require_auth" var
SetEnvIf Request_URI ^/pretty/url require_auth=true
# Auth stuff
AuthUserFile /var/www/htpasswd
AuthName "Password Protected"
AuthType Basic
# Setup a deny/allow
Order Deny,Allow
# Deny from everyone
Deny from all
# except if either of these are satisfied
Satisfy any
# 1. a valid authenticated user
Require valid-user
# or 2. the "require_auth" var is NOT set
Allow from env=!require_auth

它与单个漂亮的 URL 配合得很好。但是我无法找到一种方法来使其适应许多URL,每个URL都通过htpasswd具有不同的用户。

只需通过 php 发送身份验证标头,然后就会弹出身份验证窗口。在您的代码中,您可以检查不同的用户并请求 uri。在此示例中,它仅检查用户,但您也可以比较REQUEST_URI或参数。它应该只向你展示这个概念。

<?php
    if (!isset($_SERVER['PHP_AUTH_USER'])) {
        header("WWW-Authenticate: Basic realm="Private Area"");
        header("HTTP/1.0 401 Unauthorized");
        print "Sorry - you need valid credentials to be granted access!n";
        exit;
    } else {
        if (preg_match('/^/pretty/url/', $_SERVER["REQUEST_URI"], $matches) && $_SERVER['PHP_AUTH_USER'] == 'paul') {
            print "Welcome to the private area!";
        } else {
            header("WWW-Authenticate: Basic realm="Private Area"");
            header("HTTP/1.0 401 Unauthorized");
            print "Sorry - you need valid credentials to be granted access!n";
            exit;
        }
    }
?>

最新更新