22/08/2015 - LINUX
Instead of writing a login script for an application to handle users, you can just use .htaccess and .htpasswd to do it all for you. For more information, visit this and this.
We want:
user-1
to access only to site-1
with http://test.local/site-1
user-2
to access only to site-2
with http://test.local/site-2
hello
site-1
index.php
site-2
index.php
index.php
Use this link to create .htaccess file and this link to create .htpasswd file. Assuming that your project root is /var/www/html/local/hello/
and your users are user-1
and user-2
. Your files should like below.
Goes into project root.
AuthType Basic
AuthName "Protected Site"
AuthUserFile /var/www/html/local/hello/.htpasswd
Require valid-user
Goes into project root.
user-1:$apr1$CraA.0n7$JRqS7GyggMKNYcTP65rAW/
user-2:$apr1$2QIlucFc$auT3J0uJmBjhY0axRrVnJ.
Goes into site-1
folder.
AuthUserFile /var/www/html/local/test/.htpasswd
Require user user-1
Goes into site-2
folder.
AuthUserFile /var/www/html/local/test/.htpasswd
Require user user-2
inanzzz@inanzzz:/ $ sudo nano /etc/apache2/sites-available/hello.local.conf
# Config content
<VirtualHost *:80>
ServerName hello.local
ServerAlias www.hello.local
ServerAdmin admin@hello.local
DocumentRoot /var/www/html/local/hello
<Directory /var/www/html/local/hello>
AllowOverride AuthConfig
Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
Order allow,deny
Allow from all
</Directory>
ErrorLog ${APACHE_LOG_DIR}/hello.local.error.log
CustomLog ${APACHE_LOG_DIR}/hello.local.access.log combined
</VirtualHost>
inanzzz@inanzzz:/ $ sudo a2ensite hello.local.conf
inanzzz@inanzzz:/ $ sudo nano /etc/hosts
# Hosts content
127.0.0.1 hello.local
inanzzz@inanzzz:/ $ sudo services apache2 restart
hello
site-1
index.php
.htaccess # user-1 specific one
site-2
index.php
.htaccess # user-2 specific one
index.php
.htaccess
.htpasswd
if (isset($_SERVER['PHP_AUTH_USER']) && in_array($_SERVER['PHP_AUTH_USER'], ['user-1', 'user-2'])) {
header('location: /'.substr($_SERVER['PHP_AUTH_USER'], -1));
exit;
}
If you access http://hello.local
address you'll be prompted to enter your login details. Based on what you entered, you'll be redirected to only your resources and be blocked for accessing to other users' resources.