Apache Basic Auth Redirect
Jump to navigation
Jump to search
Purpose
In this scenario I needed to authenticate users, then redirect them to their specific directories to retrieve files. I was asked last minute to take care of this and had to pull together something.
Process
Apache does not allow you to create if statements for the REMOTE_USER variable[1], so this required the use of a php index file that would read the variable and redirect accordingly.
- Created a landing directory that would prompt for credentials.
- Then had any request made of the document root redirected to the landing page.
- The last part of the vhost was the authentication needed for each user directory (This should be replaced with .htaccess files, as these are reread without a server restart)
<VirtualHost *:80>
ServerName dev2.domain.tld
DocumentRoot /var/www/html/files
<if "%{REQUEST_URI} == '/'">
Redirect "/" "http://dev2.domian.tld/landing"
</if>
<Directory "/var/www/html/files/landing">
AuthType Basic
AuthName "Restricted"
AuthBasicProvider file
AuthUserFile "/etc/httpd/passwords"
Require valid-user
</Directory>
<Directory "/var/www/html/files/testuser1">
AuthType Basic
AuthName "Restricted"
AuthBasicProvider file
AuthUserFile "/etc/httpd/passwords"
Require user user1
</Directory>
At this point I created the htaccess file and user credentials (for testing I used defaults, but you should replace md5 with bcrypt).[2]
htpasswd -c /etc/httpd/passwords user1 New password: Re-type new password: Adding password for user user1 htpasswd /etc/httpd/passwords user2 New password: Re-type new password: Adding password for user user2
Then the last piece was to create the index.php file. I know nothing about php so some additional googling was needed.[3][4][5][6][7]
vi /var/www/html/files/landing/index.php
<html>
<head>
<body>
<?php
$user=$_SERVER['REMOTE_USER'];
if ($user=="user2") {$site="http://dev2.domain.tld/testuser2";}
elseif ($user=="user1") {$site="http://dev2.domain.tld/testuser1";}
header( "Location: $site ");
?>
</body>
</head>
</html
- ↑ https://httpd.apache.org/docs/current/mod/mod_rewrite.html
- ↑ https://httpd.apache.org/docs/2.4/howto/auth.html
- ↑ https://www.w3schools.com/php/php_if_else.asp
- ↑ http://forums.devshed.com/php-development-5/remote_user-redirect-62855.html
- ↑ https://www.thoughtco.com/how-to-redirect-with-php-2693922
- ↑ https://www.w3schools.com/php/func_string_echo.asp
- ↑ http://php.net/manual/en/function.sleep.php