Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use HTTP Auth only if accessing a specific domain

I've got several sites: example.com, example1.com, and example2.com. All of them point to my server's /public_html folder, which is my Apache root folder.

What do I need to add to my .htaccess file to use http authentication only if the user is coming from example2.com? example.com and example1.com should NOT use authentication.

I know I need something like

AuthType Basic
AuthName "Password Required"
AuthUserFile "/path/to/.htpasswd"
Require valid-user

But I only want to require a password if the user is visiting example2.com.

Edit

Using an approach suggested in an answer, I have the following in my .htaccess file:

SetEnvIfNoCase Host ^(.*)$ testauth
<IfDefine testauth>
RewriteRule ^(.*)$ index2.php?q=$1 [L,QSA]
</IfDefine>

I know that the mod_setenvif.c module is enabled (I verified with an <IfModule> block), but it would appear that "testauth" is never getting defined, because my test to verify (redirecting to index2.php) is not executing (whereas it was getting executed in my <IfModule> block). Any ideas why?

like image 385
Dave DeLong Avatar asked Aug 31 '09 21:08

Dave DeLong


People also ask

How do I set basic authentication in HTTP?

To configure your web service client to use HTTP basic authentication, supply the HttpTransportProperties. Authenticator object in your client Java code, and specify a user name and a password. Set this configuration as an option of the web service client.

What is an important thing to keep in mind if using the basic authentication type in Apache?

It is important to be aware, however, that Basic authentication sends the password from the client to the server unencrypted. This method should therefore not be used for highly sensitive data, unless accompanied by mod_ssl . Apache supports one other authentication method: AuthType Digest .


1 Answers

How about something along the lines of this in the htaccess file in the document root:

# set the "require_auth" var if Host ends with "example2.com"
SetEnvIfNoCase Host example2\.com$ 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

This will make it so authentication is not required unless the host ends with example2.com (e.g. www.example2.com, dev.example2.com, etc). The expression can be tweaked if needed. Any other host will cause the require_auth var not to get set so authentication is not required. If this needs to be the other way around, the last line could be changed to: Allow from env=require_auth, removing the !.

like image 139
Jon Lin Avatar answered Sep 21 '22 15:09

Jon Lin