Create .
htaccess file with password protection
Last Updated Tue, Mar 26 2019 11:32 AM
How to create .htaccess file with username and password to protect web directory
1. Navigate to www folder
# cd /var/www
2. Create a test folder in www to keep web content
# mkdir testfolder
3. Create .htaccess file within testfolder using text editor and enter the code within it
# nano .htaccess
## Enter the following code in .htaccess file
AuthUserFile /var/www/testfolder/.htpasswd
AuthGroupFile /www.null
AuthName "Authorization Required"
AuthType Basic
require user web
Order allow,deny
Allow from 115.115.146.200 # Enters IPs from where access is allowed
satisfy any
Options +FollowSymLinks
DirectoryIndex index.php
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
## Save the file
4. Now create the .htpasswd password file for the user web
# htpasswd -c .htpasswd web
PUT YOUR PASSWORD
5. Now create a vhost in apache and point to the web directory and test.
# cd /etc/apache2/sites-available
# nano test.com.conf
## Enter the following in test.com.conf file
AccessFileName /var/www/testfolder/.htaccess
ServerAdmin webmaster@localhost
DocumentRoot /var/www/test.com/public_html
ServerName www.test.com
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
Options Indexes FollowSymLinks Includes
AllowOverride All
Order allow,deny
Allow from all
--------------------------------------
## FINISH