I have a site with links like this:
etc.
I would like to have htaccess password protection for a specific ID, say 200.
How can I do this?
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
}
}
来源:https://stackoverflow.com/questions/19491680/protect-a-url-with-http-authentication-based-on-query-string-parameter