Protect a url with HTTP authentication based on query string parameter
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=200RewriteCond %{QUERY_STRING} (?:^|&)id=(200|1)(?:&|$) [NC]RewriteRule ^(index\.php)/?$ $1/%1 [NC]# set SECURED var to 1 if URI is /index.php/200SetEnvIfNoCase Request_URI "^/index\.php/(200|1)" SECURED# enforce auth if SECURED=1AuthType BasicAuthName "Login Required"AuthUserFile /full/path/to/passwordsRequire valid-userOrder allow,denyAllow from allDeny from env=SECUREDSatisfy 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 }}