Restrict Access to a Specific URL

Using the or directives to restrict access to specific areas of a website only works if there is actually a physical file or directory. But as more and more site frameworks are using rewritten URLs, the chances of a URL mapping to a physical file or directory are getting pretty slim.

So, what can you do in these circumstances?

Well, something like this:

Satisfy any
 
Order allow,deny
 
SetEnvIf Request_URI "^/admin" admin
Deny from env=admin
 
AuthUserFile /var/www/your-website/.htpasswd
AuthType Basic
AuthName "Authentication Required"
 
Require valid-user
 
Allow from all

This configuration essentially sets the site up to be completely open by default ('Order allow,deny' and 'Allow from all').

Then, we conditionally set an environment variable using the SetEnvIf directive. The environment variable 'admin' is only set if the requested URI starts with /admin (in Apache, the requested URI is the URL after the host name).

Since we have the directive 'Order allow,deny', anyone accessing the admin section of the website will be denied due to the 'Deny from env=admin' directive. This then forces users to authenticate before they can access this URL.

Joint Credit

My colleague John Croucher worked with me to help figure this one out after we were asked to restrict access to a URL on a site using rewritten addresses this week.