Password protect a specific URL

BadHorsie picture BadHorsie · Jan 30, 2013 · Viewed 71.5k times · Source

The site is on shared hosting. I need to password protect a single URL.

http://www.example.com/pretty/url

Obviously that's not a physical file path I'm trying to protect, it's just that particular URL.

Any quick solution with .htaccess?

Answer

Jon Lin picture Jon Lin · Jan 30, 2013

You should be able to do this using the combination of mod_env and the Satisfy any directive. You can use SetEnvIf to check against the Request_URI, even if it's not a physical path. You can then check if the variable is set in an Allow statement. So either you need to log in with password, or the Allow lets you in without password:

# Do the regex check against the URI here, if match, set the "require_auth" var
SetEnvIf Request_URI ^/pretty/url require_auth=true

# Auth stuff
AuthUserFile /var/www/htpasswd
AuthName "Password Protected"
AuthType Basic

# Setup a deny/allow
Order Deny,Allow
# Deny from everyone
Deny from all
# except if either of these are satisfied
Satisfy any
# 1. a valid authenticated user
Require valid-user
# or 2. the "require_auth" var is NOT set
Allow from env=!require_auth