How to Configure Your Website Using htaccess in Linux with Apache Step by Step
.htaccess
files (or “distributed configuration files”) provide a way to make configuration changes on a per-directory basis. A file, containing one or more configuration directives, is placed in a particular document directory, and the directives apply to that directory, and all subdirectories thereof.
Step by Step
For this to work successfully you will have to be logged in as root or using one of the sudo
or su
options.
Step 1:
We will need to create a folder that will have to be authenticated. Since the default location in Apache is /var/www/html
we will create it here. You will do this by using the mkdir
command.
1 | [root@linux ~]# mkdir /var/www/html/testfolder |
Step 2:
Next, we need to add the .htaccess &
.htpasswd
files to the personal folder. We first need to change the directory of the folder we wish to protect.
1 | [root@linux ~]# cd /var/www/html/testfolder |
Step 3:
Next, we can create the .htaccess file.
1 | [root@linux ~]# vi .htaccess |
Step 4:
Press i
to insert and add the following content.
1 2 3 4 5 | AuthUserFile /var/www/html/testfolder/.htpasswd AuthGroupFile /www.null AuthName "Authorization Required" AuthType Basic require user USER_NAME |
Step 5:
Change “test folder
” to the name of your folder and change “USER_NAME
” to the user name you wish to use.
Step 6:
Press your esc
button then: wq to save your file in your
vi
editor.
Step 7:
Next, we’ll create the .htpasswd file. We want to run htpasswd on the path of the folder we want to protect.
1 | [root@linux ~]# htpasswd -c /var/www/html/testfolder/.htpasswd USER_NAME |
Step 8:
You should see something like this:
1 2 3 4 | [root@linux ~]# htpasswd -c /var/www/html/testfolder/.htpasswd USER_NAME New password: Re-type new password: Adding password for user USER_NAME |
Step 9:
Verify that this file was created in your test folder directory. To do this use “ls -a
” in your command prompt.
Step 10:
Next, we will have to edit the Apache httpd
.conf (on some systems called the apache2.conf) file.
1 | [root@linux ~]# vi /etc/httpd/conf/httpd.conf |
Step 11:
You will have to scroll all the way to the bottom to add the following directory.
1 2 3 4 | #FOR MY TEST FOLDER <Directory "/var/www/html/testfolder"> AllowOverride AuthConfig </Directory> |
Step 12:
Finally, save httpd.conf by typing esc: qw!
and restart apache.
1 | [root@linux ~]# service httpd restart |