Htaccess protection for some subdomain folders only

.htaccesshostingsubdomain

I have two site hosted as subdomains.

One of the site use subdomains as aliases for dynamic images requests.

site1.example.com
site2.example.com
sub1.example.com -> same as site1
sub2.example.com -> same as site1
sub3.example.com -> same as site1

Dynamic images are requested by subX.example.com/images.php?.

In the htaccess I want to:

  • limit access to site1 and site2 (same user and password)
  • have no authentication prompt on subXs
  • redirect everything to images.php for subXs requests

Limitations:
I don't have access to httpd.conf so no directory block

I tested SetEnv, SetEnvIf, IfDefine with no success.

Best Answer

To handle the first 2 items, you need to use the SetEnvIf along with a Satisfy, something like this:

SetEnvIf Host site1.example.com need_auth
SetEnvIf Host site2.example.com need_auth

Order allow,deny

# setup whatever auth stuff you need here
AuthName "Private"
AuthType Basic
AuthBasicProvider file
AuthUserFile /etc/apache2/pwd

# here's where you actually check the credentials and env
Require valid-user
Allow from env=!need_auth
Satisfy Any

To do the redirect, you can use mod_rewrite. I'm not exactly sure what you mean, but if you want everything redirected to images.php, you can do something like:

RewriteCond %{ENV:need_auth} ^.*$
RewriteRule ^(.*)$ http://site1.example.com/images.php [R]

It would probably be a lot easier if you added a RedirectMatch in the vhost file for the subX.example.com domains. The .htaccess file is designed to be per-directory based configuration, and not host-based. It's not really designed to do the things you're asking.

Related Topic