Dynamic Host Configuration Protocol (DHCP) is a protocol to dynamically giva an IP address to different devices. In cisco, defining DHCP is following these steps:

  1. Define DHCP exclude-address: We separate unwanted address in DHCP

  2. Define DHCP Pool : We define DHCP pool which is assigned to clients

  3. Define network, dns-server and default router

SW1# conf t
SW1(config)#ip dhcp excluded-address 192.168.10.1 192.168.10.10
SW1(config)#ip dhcp pool HRT
SW1(dhcp-config)#network 192.168.10.0
SW1(dhcp-config)#dns-server 4.2.2.4 8.8.8.8
SW1(dhcp-config)#default-router 192.168.10.1
1-1 What’s port Security

In Cisco switches, you can limit PCs based on their Mac-address. Port security enhances the security in Cisco devices

Let’s implement a scenario to learn more about port security:

Senario 1: In company A, we want to define port-security to learn mac-address of all PCs on the nework and maximum each port has to learn maximum two mac-address. In a case of violation, ports should shutdown immediately.

SW1# conf t
SW1(config)# int range fa0/1-24
SW1(config-if)# switchport mode access
SW1(config-if)# switchport port-security maximum 2
SW1(config-if)# switchport port-security mac-address sticky
SW1(config-if)# switchport port-security voilation shutdown
SW1(config-if)# switchport port-security

port security voilation has three modes:

  • shutdown: This is a default mode. It’ll shutdown the interface.

  • protect: Allow traffic from valid mac-address but block traffic from invalid.

  • restrict: Assist with troubleshooting by keeping count of voilations.

You can define static mac-address with this command:

SW1(config-if)# switchport port-security mac-address ——-Mac-address————–

In real scenario, network administrators define auto recovery for port security. It means in case of violation, ports automatically enable timer to recover from psecure violation disable state:

SW1(config)# errdisable recovery cause psecure-violation

also we can define timer interval(second), to recover automatically:

SW1(config)# errdisable recovery interval 30
1-2 Show Port Security

You can use these commands to see port security:

SW1(config)# show port-security
or
SW1(config)# show port-security int fa0/1

SSH, also known as Secure Socket Shell, is a network protocol that provides administrators with a secure way to access a remote computer.

To have a secure connection to Cisco devices, we don’t use Telnet. Because Telnet sends the password in plain Text. If you use kind of sniffer tools such as Wireshark, you can see exact password is passing to the device. So, for having secure connection all system administrators use SSH.

There are 5 steps for creating SSH connection, which are namely:

  1. Create a hostname

  2. Create a domain name

  3. Generate RSA key

  4. Create a local account

  5. Allow SSH in vty line

SW1# conf t
SW1(config)# hostname SW1
SW1(config)# ip domain name HRT
SW1(config)# crypto gen key rsa
SW1(config)# ip ssh version 2
SW1(config)# username mona password/secret cisco
SW1(config)# line vty 0 5
SW1(config-line)# transport input telnet/ssh/all
SW1(config-line)# login local

In line 4, length of RSA key depends on the device. Some devices support more than 1024 or 2048.

In line 6, you can use password or secret, as I told you in previous section, secret encrypts your password in running-config, but password is shown in clear text.

In line 8, you can select telnet, ssh or both of them to allow in vty line. In other words, if you select all, ssh users and telnet users can connect through vty line

1-1 What is VTP?

VTP is a layer 2 messaging protocol which is a Cisco proprietary protocol that propagates the definition of Virtual Local Area Networks (VLAN) on the whole local area network. VTP minimizes misconfigurations and configuration inconsistencies that can result in a number of problems, such as duplicate VLAN names, incorrect VLAN-type specifications, and security violations.

There are three versions of VTP, namely version 1, version 2, version 3. All feature of 3 versions of VTP is shown in Table1

VTP V1

VTP V2

VTP V3

Feature

*

VTP password

*

Private Vlan

*

Extended Vlan

*

Token Ring Support

There are three main modes in VTP:

  • Server : This is a default mode of VTP. You can create, modify, and delete VLANs and specify other configuration parameters (such as VTP version and VTP pruning) for the entire VTP domain. VTP servers advertise their VLAN configuration to other network devices

  • Client: VTP clients behave the same way as VTP servers, but you cannot create, change, or delete VLANs on a VTP client.

  • Transparent: VTP transparent network devices do not participate in VTP. A VTP transparent network device does not advertise its VLAN configuration and does not synchronize its VLAN configuration based on received advertisements. However, in VTP version 2, a transparent network device will forward received VTP advertisements from its trunking LAN ports. In VTP version 3, a transparent network device is specific to an instance.

Example:

Enter a caption for this image (optional)

We want to make a Vlan in Switch 1 and change its mode to server mode. Between Switch 1 and Switch 2, we use trunk port and then set Switch 2 mode for VTP to client.

switch1(config)# int gi0/1
switch1(config-if)# switchport mode trunk
switch1(config)# vlan 10
switch1(config-if)# name IT
switch1(config-if)# exit
switch1(config)# vlan 20
switch1(config-if)# name Sales
switch1(config-if)# exit
switch1(config)# vtp mode server
switch1(config)# vtp domain HRT
switch2(config)# int gi0/1
switch2(config-if)# switchport mode trunk
switch2(config)# vlan 10
switch2(config-if)# name IT
switch2(config-if)# exit
switch2(config)# vlan 20
switch2(config-if)# name Sales
switch2(config-if)# exit
switch2(config)# vtp mode client
switch2(config)# vtp domain HRT

to see status of VTP:

switch1# show vtp status

Enter a caption for this image (optional)

Now if you check, switch2 , you can see Vlan 10, 20 are made automatically.

in VTP V3, you can define password VTP. In doing so, just switches with the same password can talk eachother.

switch(config)# vtp password cisco
1-2 VTP Pruning

VTP pruning enhances network bandwidth use by reducing unnecessary flooded traffic, such as broadcast, multicast, unknown, and flooded unicast packets. VTP pruning increases available bandwidth by restricting flooded traffic to those trunk links that the traffic must use to access the appropriate network devices. By default, VTP pruning is disabled.

Without VTP Pruning
Enter a caption for this image (optional)

With VTP Pruning
Enter a caption for this image (optional)

As you can see in above pictures, traffic with and without VTP Pruning is demonstrated. To enable VTP pruning:

switch(config)# vtp pruning

To enable VTP V2 or V3, you have to write:

switch(config)# vtp version 2 or 3

In Cisco we have two types of access-list:

  • Standard

    • It’s based on source address

    • It uses lower process utilization

  • Extended

    • It’s based on source/destination and port number

    • It uses high process utilization

We define access-list only on routers or layer3 switches. You can’t define access-list on layer 2 switches

1-1 Standard Acess-list

Enter a caption for this image (optional)

Imagine in router 2, we want to deny any packets come from network 192.168.3.0/24. To prevent these packet based on standard access-list just pay attention to source:

Router2(config)# access-list 10 deny 192.168.3.0 0.0.0.255
Router2(config)# access-list 10 permit any
Router2(config)# int gi0/1
Router2(config-if)# ip access-group 10 in

In this command, first, we define access-list and write it as 10. This number should between 1 to 99 . Then, we deny every source address in network 192.168.3.0/24. In access-list, we always use wildcard mask instead of netmask. To know wildcard mask, just substract 255.255.255.255 from network mask , the result shows wildcard mask.

Next, we permit others to access network. If you forget to write line 2, all network will be down. Because you forbid any connections from router 2.

After that, we have to associate access-list to router interface. We have inbound and outbound, in this example, we are entering from network 192.168.3.0/24 to router 2. So, we write access-list in inbound of router.

1-2 Extended Access-list

Enter a caption for this image (optional)

The best practise we can bring here, is our previous router-on-a-stick. In above example, we have two PCs which can communicate together through router 0. Switch 0 is connected to Router0 through trunk port. PCs IP address is:

  • PC0

    • IP Address: 192.168.10.2

    • Netmask: 255.255.255.0

    • Default Gateway: 192.168.10.1

  • PC1

    • IP Address: 192.168.20.2

    • Netmask: 255.255.255.0

    • Default Gateway: 192.168.20.1

Now, we want to forbid every packet goes from vlan 10 to vlan 20 and vice versa. So, we can define access-list based on source and destination. In extended access-list, you have to follow these rules:

1- Protocol –> Source Address–> Destination Address –> Port

2- Extended access-list starts from 100-199

Router0(config)# access-list 100 deny ip 192.168.10.0 0.0.0.255 192.168.20.0 0.0.0.255
Router0(config)# access-list 100 permit ip any any

This is for Vlan 10 which bans every packet from network 192.168.10.0/24 to 192.168.20.0/24. We define protocol, IP. It means, any related protocol to IP such as ftp, web, ….. In other words, I ban all protocols of IP.

For Vlan 20, we have:

Router0(config)# access-list 101 deny ip 192.168.20.0 0.0.0.255 192.168.10.0 0.0.0.255
Router0(config)# access-list 101 permit ip any any

Then, we access above-mentioned access-list to int fa0/0.10 and fa0/0.20:

Router0(config)# int fa0/0.10
Router0(config-subif)# ip access-group 100 in
Router0(config-subif)# exit
Router0(config)# int fa0/0.20
Router0(config-subif)# ip access-group 101 in
Router0(config-subif)# exit

There are different scenarios in access-list and it can be permit and deny or any protocol such as ftp, web. Imagine in above example just we want to deny telnet and ssh. Then, we write:

Router0(config)# access-list 100 deny tcp 192.168.10.0 0.0.0.255 192.168.20.0 0.0.0.255 eq 23
Router0(config)# access-list 100 deny tcp 192.168.10.0 0.0.0.255 192.168.20.0 0.0.0.255 eq 22
Router0(config)# access-list 100 permit ip any any
1-3 Show access-list

To know, what we write and how access-list work, just write :

Router0# show access-lists

Enter a caption for this image (optional)
1-4 Named access-list

You can define, named access-list like numbered access-list in section 1-2 and 1-1. I write previous example in named access-list:

Router0(config)# ip access-list extended vlan10
Router0(config-ext-nacl)# deny ip 192.168.10.0 0.0.0.255 192.168.20.0 0.0.0.255
Router0(config-ext-nacl)# permit ip any any
Router0(config-ext-nacl)# exit
Router0(config)# ip access-list extended vlan20
Router0(config-ext-nacl)# deny ip 192.168.20.0 0.0.0.255 192.168.10.0 0.0.0.255
Router0(config-ext-nacl)# permit ip any any
Router0(config-ext-nacl)# exit
Router0(config)# int fa0/0.10
Router0(config-subif)# ip access-group vlan10 in
Router0(config-subif)# exit
Router0(config)# int fa0/0.20
Router0(config-subif)# ip access-group vlan20 in
Router0(config-subif)# exit

As you can see, everything is the same as numbered access-list. In real work, network engineers prefer using named access-list rather than numbered access-list

Router-On-a-stick
Enter a caption for this image (optional)

To connect several vlans together, there is a model which is called “Router-on-a-stick“. This model has some advantages:

  • Cost effective

  • Easy to Implement

On the other hand, there are some drawbacks in this model:

  • Congestion on link(bottleneck on trunk port)

  • If router becomes down, network will down

switch(config)# int gi0/1
switch(config-if)# switchport mode trunk
router(config)# int gi0/0.10
router(config-subif)# encapsulation dot1Q 10
router(config-subif)# ip address 192.168.10.1 255.255.255.0
router(config)# int gi0/0.20
router(config-subif)# encapsulation dot1Q 20
router(config-subif)# ip address 192.168.20.1 255.255.255.0
router(config)# int gi0/0.30
router(config-subif)# encapsulation dot1Q 30
router(config-subif)# ip address 192.168.30.1 255.255.255.0

In Switch layer2, we use router-on-a-stick to connect vlans together based on access-list we define.

Layer 3 switches

Multilayer Switch
Enter a caption for this image (optional)

As it is shown, first set an IP address for the PC0 and PC1. PC0 is on Vlan 10, while PC1 is on Vlan 20. Default Gateway of both PCs are set with the IP address of Vlan in Switch. For routing between to Vlan, Just we use “ip routing” command as it is shown in below code:

switch(config)# vlan 10
switch(config-if)# ip address 192.168.10.254 255.255.255.0
switch(config-if)# exit
switch(config)# vlan 20
switch(config-if)# ip address 192.168.20.254 255.255.255.0
switch(config-if)# exit
switch(config)# ip routing
1-1 What’s Trunk port?

A trunk port is a port that is assigned to carry traffic for all the VLANs.Trunk send Untagged and Tagged information. There are two standards for Trunking:

  • ISL(Cisco)

  • 802.1Q(Industry Standard) is 4 Byte which is considered without Native Vlan

Example:

Trunk between two switches
Enter a caption for this image (optional)
sw1(config)# int fa0/1
sw1(config-if)# switchport mode trunk
sw2(config)# int fa0/1
sw2(config-vlan)# switchport mode trunk

In older version of Cisco devices first you have to write:

switchport encapsulation dot1q

then

switchport mode trunk

1-2 Changing Native Vlan

For changing Native Vlan just write:

sw1(config)# int fa0/1
sw1(config-if)# switchport trunk native vlan 20
1-3 Allow Specific Vlan

To allow specific vlan just write:

sw1(config)# int fa0/1
sw1(config-if)# switchport allowed vlan 10,20,30

In above-mentioned code, just vlan 10, 20, 30 allowed through trunk port

You can use switchport command with add/all/except/none

sw1(config-if)# switchport allowed vlan 10,20,30
sw1(config-if)# switchport allowed vlan add/all/except/none 10,20,30
1-4 How to see trunk port
switch# show interface trunk
or
switch# show interface fa0/1 switchport

A virtual LAN (Local Area Network) is a logical subnetwork that can group together a collection of devices from different physical LAN.

1-1 Create VLAN

Imagine that we have different departments on your company and you want to separate each department based on their employees. So, with the VLAN concept you can create a VLAN and then assign different ports to these VLANs.

Vlan 10-20-30 in Switch1
Enter a caption for this image (optional)

In the above picture, we have 3 departments, each of which is assigned to unique VLAN. let’s configure switch:

sw# conf t
sw(config)# vlan 10
sw(config-vlan)# name Management
sw(config-vlan)# exit
sw(config)# vlan 20
sw(config-vlan)# name IT
sw(config-vlan)# exit
sw(config)# vlan 30
sw(config-vlan)# name SALES
sw(config-vlan)# exit

For viewing created VLANs, we enter this command:

sw# show vlan

Enter a caption for this image (optional)

VLAN 1 is a default VLAN in Cisco devices. VLAN from 1002-1005 are for other protocols. VLAN from 1006- 4094 is called Extended VLAN.

1-2 Access Switch Ports to Vlan

In above picture, a PC in VLAN 10 is connected to port Fa0/1 switch. So, we can write this command to access port Fa0/1 to VLAN 10:

sw(config)# int fa0/1
sw(config-vlan)# switchport mode access
sw(config-vlan)# switchport access vlan 10
sw(config-vlan)# exit

Now, if we enter show vlan:

Enter a caption for this image (optional)

Now we do it for other ports:

sw(config)# int fa0/2
sw(config-vlan)# switchport mode access
sw(config-vlan)# switchport access vlan 20
sw(config-vlan)# exit
sw(config)# int fa0/3
sw(config-vlan)# switchport mode access
sw(config-vlan)# switchport access vlan 30
sw(config-vlan)# exit

and the result is:

Enter a caption for this image (optional)
1-3 Native Vlan

By default in Cisco switches , Vlan 1 is a native Vlan. It means, untagged traffic carries in this vlan. We’ll know how to change Native Vlan.

Intro

In this section learn how to set initial configuration in Cisco devices. You can also follow the video of this section on my channel on YouTube.

We have 3 modes in Cisco devices, namely:

Modes

Symbols

command

User mode

switch>

Privilege mode

switch#

enter enable in user mode

Global mode

switch(config)#

enter config terminal or conf t to enter this mode

In privilege mode, you can run show commands, while in global mode you can change configuration of switch.

1-1 Setting hostname
sw# conf t
sw(config)# hostname Cisco
1-2 Setting password for line console

Console to PC
Enter a caption for this image (optional)
sw# conf t
sw(config)# line console 0
sw(config)# password CISCO
sw(config)# login

In line 4, if you forget to write login, switch will not ask any password. So, you have to write it, to enable password in line console 0.

1-3 Setting password for line vty

vty lines are using for users to connect via SSH, Telnet. In other words, to enable SSH or Telnet, you have to use these lines. By default, Cisco breaks up vty lines into two segments:

  • vty 0 – 4 (older devices)

  • vty 5- 15

sw# conf t
sw(config)# line vty 0 15
sw(config)# password CISCO
sw(config)# login

New devices have more than 15 vty. Usually system administrator define 5 vty in devices.

1-4 Setting password for the privilege mode

we have two options for setting password for the privilege mode:

  • password which is in clear mode

  • secret which is encryption mode

sw# conf t
sw(config)# enable password CISCO

or

sw# conf t
sw(config)# enable sercret CISCO
1-5 Encrypt your Cisco device

if you use password instead of secret with # show running-config command you can see the clear password. To encrypt the password use this command:

sw# conf t
sw(config)# service password-encryption

now if you look at running-config , everything has become encrypted.

encrypted password
Enter a caption for this image (optional)
1-6 Setting IP address for default vlan

by default, all Cisco devices have vlan 1, so in other section will know how to make a vlan. In this code, we set IP address 192.168.1.1 with subnet mask 255.255.255.0. Then, we use command no shutdown to enable interface.

sw# conf t
sw(config)# int vlan 1
sw(config-if)# ip address 192.168.1.1 255.255.255.0
sw(config-if)#no shutdown

Cisco recommends all use any vlan number except vlan 1.

1-7 Setting default gateway

if you have router and you want to access your Cisco switch to router for the Internet, you have to set default gateway.

sw# conf t
sw(config)# ip default-gateway 192.168.1.254
1-8 Shutdown ports

you can shutdown ports for the range of ports. For example, range of 1 to 4 is shutdown by shutdown command.

sw# conf t
sw(config)# int range fa0/1-4
sw(config)# shutdown

use no shutdown or no shut to enable ports

1-9 Setting banner

you can set a banner for a switch with motd command. After motd you have to use kind of character and it can be * + | or anything. The important matter is that both character should be the same as the code it is shown

sw# conf t
sw(config)# banner motd +
******************************************
cisco 3850 by HRT
​******************************************
+

Enter a caption for this image (optional)

1-10 Prevent mistype

Enter a caption for this image (optional)

Mistype translating domain server

In Cisco devices, if you enter a some command wrong, by default try to map it to domain name and it takes 30 sec to do that. To prevent mistype, we use this command:

sw# conf t
sw(config)# no ip domain-lookup
1-11 Setting timeout

if you are working with Cisco command line, you can set session timeout with these command. In these examples, we set timeout to 10 seconds.

vty line:

sw# conf t
sw(config)# line vty 0 5
sw(config)# exec-timeout 0 10

line console:

sw# conf t
sw(config)# line cosole 0
sw(config)# exec-timeout 0 10
1-12 save configuration

to save your configuration you can run these two commands:

sw# copy running-config startup-config

or

sw# write

 

The first question is asked by those who are using Cisco devices for the first time is that how can I connect to Cisco devices. It needs kind of cable which is called rollover cable.

Rollover cable
Enter a caption for this image (optional)

rollover cable contains RJ-45 and RS-232 and as it is demonstrated in below picture, RJ-45 is connected to switch and on the other hand RS-232 is connected to PC.

Console to PC
Enter a caption for this image (optional)

Today’s PCs usually don’t have RS-232 port. You have to buy kind of convertor for RS-232 to USB or you can use new rollover cable which is RJ45 to USB.

you can use kind of these software in PC to connect to switch through the console port. Putty is a famous software which supports SSH, Telnet, Serial.

I’ve uploaded a video in Youtube to become familiar how to connect rollover cable to switch and how to connect switch through Putty

Enter a caption (optional)
Hamidreza Talebi, linux

Introduction

When running a website, there are often parts of the site that you’ll want to restrict from visitors. Web applications may provide their own authentication and authorization methods, but the web server itself can also be used to restrict access if these are inadequate or unavailable.

In this guide, we’ll demonstrate how to password-protect assets on an Apache web server running on Ubuntu 16.04.

Prerequisites

In order to complete this tutorial, you will need access to an Ubuntu 16.04 server.

In addition, you will need the following before you can begin:

  • A sudo user on your server: You can create a user with sudo privileges by following the Ubuntu 16.04 initial server setup guide.
  • An Apache2 web server: If you haven’t already set one up, the Apache section of the in-depth article, How To Install Linux, Apache, MySQL, PHP (LAMP) stack on Ubuntu 16.04
    , can guide you.
  • A site secured with SSL: How you set that up depends on whether you have a domain name for your site.
    • If you have a domain name… the easiest way to secure your site is with Let’s Encrypt, which provides free, trusted certificates. Follow the Let’s Encrypt guide for Apache to set this up.
    • If you do not have a domain… and you are just using this configuration for testing or personal use, you can use a self-signed certificate instead. This provides the same type of encryption, but without the domain validation. Follow the self-signed SSL guide for Apache to get set up.

When all of these are in place, log into your server as the sudo user and continue below.

Step 1 — Installing the Apache Utilities Package

We will use a utility called htpasswd, part of the apache2-utils package, to create the file and manage the username and passwords needed to access restricted content.

  • sudo apt-get update
  • sudo apt-get install apache2-utils

Step 2 — Creating the Password File

We now have access to the htpasswd command. We can use this to create a password file that Apache can use to authenticate users. We will create a hidden file for this purpose called .htpasswd within our /etc/apache2 configuration directory.

The first time we use this utility, we need to add the -c option to create the specified file. We specify a username (sammy in this example) at the end of the command to create a new entry within the file:

  • sudo htpasswd -c /etc/apache2/.htpasswd sammy

You will be asked to supply and confirm a password for the user.

Leave out the -c argument for any additional users you wish to add:

  • sudo htpasswd /etc/apache2/.htpasswd another_user

If we view the contents of the file, we can see the username and the encrypted password for each record:

  • cat /etc/apache2/.htpasswd
Output
sammy:$apr1$.0CAabqX$rb8lueIORA/p8UzGPYtGs/
another_user:$apr1$fqH7UG8a$SrUxurp/Atfq6j7GL/VEC1

Step 3 — Configuring Apache Password Authentication

Now that we have a file with users and passwords in a format that Apache can read, we need to configure Apache to check this file before serving our protected content. We can do this in one of two ways: either directly in a site’s virtual host file or by placing .htaccess files in the directories that need restriction. It’s generally best to use the virtual host file, but if you need to allow non-root users to manage their own access restrictions, check the restrictions into version control alongside the website, or have a web applications using .htaccess files for other purposes already, check out the second option.

Choose the option that best suits your needs.

Option 1: Configuring Access Control within the Virtual Host Definition (Preferred)

The first option is to edit the Apache configuration and add the password protection to the virtual host file. This will generally give better performance because it avoids the expense of reading distributed configuration files. This option requires access to the configuration, which isn’t always available, but when you do have access, it’s recommended.

Begin by opening up the virtual host file that you wish to add a restriction to. For our example, we’ll be using the 000-default.conf file that holds the default virtual host installed through Ubuntu’s apache package:

  • sudo nano /etc/apache2/sites-enabled/000-default.conf

Inside, with the comments stripped, the file should look similar to this:

/etc/apache2/sites-enabled/000-default.conf
<VirtualHost *:80>
  ServerAdmin webmaster@localhost
  DocumentRoot /var/www/html
  ErrorLog ${APACHE_LOG_DIR}/error.log
  CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

Authentication is done on a per-directory basis. To set up authentication, you will need to target the directory you wish to restrict with a <Directory ___> block. In our example, we’ll restrict the entire document root, but you can modify this listing to only target a specific directory within the web space:

/etc/apache2/sites-enabled/000-default.conf
<VirtualHost *:80>
  ServerAdmin webmaster@localhost
  DocumentRoot /var/www/html
  ErrorLog ${APACHE_LOG_DIR}/error.log
  CustomLog ${APACHE_LOG_DIR}/access.log combined

  <Directory "/var/www/html">
  </Directory>
</VirtualHost>

Within this directory block, specify that we wish to set up Basic authentication. For the AuthName, choose a realm name that will be displayed to the user when prompting for credentials. Use the AuthUserFile directive to point Apache to the password file we created. Finally, we will require a valid-user to access this resource, which means anyone who can verify their identity with a password will be allowed in:

/etc/apache2/sites-enabled/000-default.conf
<VirtualHost *:80>
  ServerAdmin webmaster@localhost
  DocumentRoot /var/www/html
  ErrorLog ${APACHE_LOG_DIR}/error.log
  CustomLog ${APACHE_LOG_DIR}/access.log combined

  <Directory "/var/www/html">
      AuthType Basic
      AuthName "Restricted Content"
      AuthUserFile /etc/apache2/.htpasswd
      Require valid-user
  </Directory>
</VirtualHost>

Save and close the file when you are finished.

Before restarting the web server, you can check the configuration with the following command:

  • sudo apache2ctl configtest

If everything checks out and you get Syntax OK, then restart the server to implement your password policy. Since systemctl doesn’t display the outcome of all service management commands, we’ll use the the status to be sure the server is running:

  • sudo systemctl restart apache2
  • sudo systemctl status apache2

Now, the directory you specified should now be password protected.

Option 2: Configuring Access Control with .htaccess Files

Apache can use .htaccess files in order to allow certain configuration items to be set within a content directory. Since Apache has to re-read these files on every request that involves the directory, which can negatively impact performance, Option 1 is preferred, but if you are already using .htaccess file or need to allow non-root users to manage restrictions, .htaccess files make sense.

To enable password protection using .htaccess files, open the main Apache configuration file:

  • sudo nano /etc/apache2/apache2.conf

Find the <Directory> block for the /var/www directory that holds the document root. Turn on .htaccess processing by changing the AllowOverride directive within that block from “None” to “All”:

/etc/apache2/apache2.conf
. . .

<Directory /var/www/>
  Options Indexes FollowSymLinks
  AllowOverride All
  Require all granted
</Directory>

. . .

Save and close the file when you are finished.

Next, we need to add an .htaccess file to the directory we wish to restrict. In our demonstration, we’ll restrict the entire document root (the entire website) which is based at /var/www/html, but you can place this file in any directory where you wish to restrict access:

  • sudo nano /var/www/html/.htaccess

Within this file, specify that we wish to set up Basic authentication. For the AuthName, choose a realm name that will be displayed to the user when prompting for credentials. Use the AuthUserFile directive to point Apache to the password file we created. Finally, we will require a valid-user to access this resource, which means anyone who can verify their identity with a password will be allowed in:

/var/www/html/.htaccess
AuthType Basic
AuthName "Restricted Content"
AuthUserFile /etc/apache2/.htpasswd
Require valid-user

Save and close the file. Restart the web server to password protect all content in or below the directory with the .htaccess file and use systemctl status to verify the success of the restart:

  • sudo systemctl restart apache2
  • sudo systemctl status apache2

Step 4 — Confirming Password Authentication

To confirm that your content is protected, try to access your restricted content in a web browser. You should be presented with a username and password prompt that looks like this:

Apache2 password prompt

If you enter the correct credentials, you will be allowed to access the content. If you enter the wrong credentials or hit “Cancel”, you will see the “Unauthorized” error page:

Apache2 unauthorized error

Conclusion

Congratulations! If you’ve followed along, you’ve now set up basic authentication for your site. Apache configuration and .htaccess can do much more than basic authentication, however. To find out more about the flexibility and power available in Apache configuration, try one of these tutorials:

 

source: digitalocean.com