Protect a url with HTTP authentication based on query string parameter

醉酒当歌 提交于 2019-12-05 19:39:30

This is not straight forward but here is a way it can be done in .htaccess itself:

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

You're not going to be able to use htaccess to do this. There's a way to require authorization based on an environment variable, but you can't match against the query string using a SetEnvIf and mod_rewrite's RewriteCond happens after the auth module so even if you match against it, the auth will already have been bypassed.

You need to implement this specifically in your index.php. There's some build-ins in php that does some of this for you. So something like:

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
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!