Hello everyone!

We have been investing plenty of personal time and energy for many years to share our knowledge with you all. However, we now need your help to keep this blog running. All you have to do is just click one of the adverts on the site, otherwise it will sadly be taken down due to hosting etc. costs. Thank you.

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.


Scenario


We want:



Site structure


hello
site-1
index.php
site-2
index.php
index.php

Create .htaccess and .htpasswd


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.


.htaccess


Goes into project root.


AuthType Basic
AuthName "Protected Site"
AuthUserFile /var/www/html/local/hello/.htpasswd
Require valid-user

.htpasswd


Goes into project root.


user-1:$apr1$CraA.0n7$JRqS7GyggMKNYcTP65rAW/
user-2:$apr1$2QIlucFc$auT3J0uJmBjhY0axRrVnJ.

user-1 specific .htaccess


Goes into site-1 folder.


AuthUserFile /var/www/html/local/test/.htpasswd
Require user user-1

user-2 specific .htaccess


Goes into site-2 folder.


AuthUserFile /var/www/html/local/test/.htpasswd
Require user user-2

Create VirtualHost


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

Final site structure


hello
site-1
index.php
.htaccess # user-1 specific one
site-2
index.php
.htaccess # user-2 specific one
index.php
.htaccess
.htpasswd

Root index.php


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;
}

Test


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.