Search code examples
regexapache.htaccessmod-rewritehttp-authentication

Protect a url with HTTP authentication based on query string parameter


I have a site with links like this:

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

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

etc.

I would like to have htaccess password protection for a specific ID, say 200.

How can I do this?


Solution

  • 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