How Can We Help?
< All Docs
Print

How to Protect your Web Sites by using Username and password in Apache on CentOS.

Table of Content
How to Protect your Web Sites by using Username and password in Apache on CentOS

This article is about to Protect your Web Sites by using Username and password in Apache on CentOS. When you're in charge of online projects, you often have to limit who can see them to keep them safe from the outside world. There could be a number of reasons for this, such as the fact that you don't want search engine crawlers to see your site while it's still being built.

In this tutorial, I'll show you how to make Apache web server protect different web site directories with passwords. There are many ways to do this, but we will only talk about the two most common ones.

Requirements

To protect in Apache on CentOS you need,

  • yum repository configured Centos server
  • A super user( root) or any normal user with SUDO privileges.

Configuration to protect default site.

To protect the main web root directory /var/www/html, open your Apache’s configuration file and change to the highlighted content from the following code.

For On Apache 2.2 Version:

<Directory /var/www/html> 
Options Indexes Includes FollowSymLinks MultiViews 
AllowOverride All
Order allow,deny
Allow from all 
</Directory>

On Apache 2.4 Version:

# vi /etc/httpd/conf/httpd.conf
<Directory /var/www/html> 
Options Indexes Includes FollowSymLinks MultiViews 
AllowOverride All 
Require all granted 
</Directory>

And now after saving the file, restart the httpd service.

# systemctl restart httpd

Now, we'll use the htpasswd command to make a username and password for our protected directory. This command is used to handle basic authentication user files.

Example and syntax of the htpasswd command is as follow.

# htpasswd -c /path/filename username 

Here, -c is used to create a file in which the username and password will be saved. Note that, the password will be hashed format.

Now we will create the credential file in /etc/httpd directory for the user- useradmin

# htpasswd -c /etc/httpd/credfile useradmin 

# vi /var/www/html/.htaccess 

Now in this file add the following content.

AuthType Basic
AuthName "Restricted Access"
AuthUserFile /etc/httpd/credfile
require user useradmin

Now you can save the file and test your setup. Open your web browser and type in your IP address or domain name, such as:

http://serverip 
Prompt you will get after browsing server-ip
Enter the credentials created by htpasswd command
The default page of the site

Table of Contents