使用基于查询字符串参数的HTTP身份验证保护URL

cil*_*ili 3 regex apache .htaccess mod-rewrite http-authentication

我有一个网站,其中包含以下链接:

http://www.example.com/index.php?id=1

http://www.example.com/index.php?id=3

等等

我想为特定ID提供htaccess密码保护,比如说200.

我怎样才能做到这一点?

Jon*_*Lin 5

您将无法使用 htaccess 来执行此操作。有一种方法可以根据环境变量要求授权,但是您不能使用 a 来匹配查询字符串,SetEnvIf并且 mod_rewriteRewriteCond发生在 auth 模块之后,因此即使您匹配它,auth 也已经被绕过。

您需要在您的index.php. php有一些内置程序可以为您完成其中的一些工作。所以像:

if($_GET['id'] == "200") {
    if (!isset($_SERVER['PHP_AUTH_USER'])) {
        header('WWW-Authenticate: Basic realm="My Realm"');
        header('HTTP/1.0 401 Unauthorized');
        echo 'Text to send if user hits Cancel button';
        exit;
    } else {
        // check username/password here
    }
}
Run Code Online (Sandbox Code Playgroud)


anu*_*ava 5

这不是直截了当的,但这是一种可以自行完成的方法.htaccess:

RewriteEngine On

# set URI to /index.php/200 if query string is id=200
RewriteCond %{QUERY_STRING} (?:^|&)id=(200|1)(?:&|$) [NC]
RewriteRule ^(index\.php)/?$ $1/%1 [NC]

# set SECURED var to 1 if URI is /index.php/200
SetEnvIfNoCase Request_URI "^/index\.php/(200|1)" SECURED

# enforce auth if SECURED=1
AuthType Basic
AuthName "Login Required"
AuthUserFile /full/path/to/passwords
Require valid-user
Order allow,deny
Allow from all
Deny from env=SECURED
Satisfy any
Run Code Online (Sandbox Code Playgroud)