Apache-2.4 Directives Configurations: Part-02
Tags: tutorial, devops, clod, productivity
Published: 2022-03-14 20:00:08

## What are directives? What are the functions of directives?

Apache directives are a set of rules which define how your server should run, the number of clients that can access your server, etc. you can configure them by using the apache2.conf or httpd.conf files.

Directives placed in the main configuration files apply to the entire server. If you wish to change the configuration for only a part of the server, you can scope your directives by placing them in `<Directory>`, `<DirectoryMatch>`, `<Files>`, `<FilesMatch>`, `<Location>`, and `<LocationMatch>` sections. These sections limit the application of the directives which they enclose to particular filesystem locations or URLs. They can also be nested, allowing for a very fine-grained configuration.

## Configuration of most important directives
List of all the available directives from official website apache2.4 - https://httpd.apache.org/docs/2.4/mod/directives.html
- Important Directives
- ServerName
- Listen
- KeepAlive
- ServerRoot
- Logging
- DocumentRoot
- Allow From
- File Inclusion
- Envars



## Detail and usage of directives

Understanding and getting basics clear, will not only saves a lot of time but also increase productivity and programming things faster. In this case, getting the basics of an apache web server and its concepts are very important because after hosting a large project or web application if the webserver needs to be scaled or needs to add some custom functions it will be very easy to implement all those configurations and easy debugging. Here are the details and usage of the default and basic directives.

> ServerName

The ServerName directive is used to define or set the name of your domain name or sub-domains.
The ServerName directive is optional and specifies what FQDN your site should answer to. The default virtual host has no ServerName directive specified, so it will respond to all requests that do not match a ServerName directive in another virtual host. 

If you have a domain name mysite.com and you wanted to host it using an apache web server, the value of the ServerName directive in the VirthuaHost configurations file should be your domain name.

```
<VirtualHost *:80>
    ServerName www.mysite.com
    DocumentRoot "/home/web-app"
    # Other directives here
</VirtualHost>
```


> Listen

Listen is the directive used to define the port Apache listens on and also any specific IP address to listen on. If the IP address is not specified, Apache2 will listen to all IP addresses assigned to the machine it runs on.

By default, Apache listens on port 80, but you can define this to a nonstandard port if needed. You can also use Listen to define specific addresses that the server will accept connections from.
 


How to listen on one port and assign multiple IP addresses to expose the webserver.
The server has two IP addresses. On one (162.0.0.40), we will serve the "main" server, server.mysite.com and on the other (162.0.0.50), we will serve two or more virtual hosts.

```
Listen 80

# This is the "main" server running on 162.0.0.40
ServerName server.mysite.com
DocumentRoot "/www/mainserver"

<VirtualHost 162.0.0.40>
    DocumentRoot "/www/example1"
    ServerName www.mysite.com
</VirtualHost>

<VirtualHost 162.0.0.50>
    DocumentRoot "/www/example2"
    ServerName www.mysite.org
</VirtualHost>

```

> How to run different sites on a different port.

```
Listen 80
Listen 8080

<VirtualHost 172.20.30.40:80>
    ServerName www.mysite.com
    DocumentRoot "/www/project-80"
</VirtualHost>

<VirtualHost 172.20.30.40:8080>
    ServerName www.mysite-2.com
    DocumentRoot "/www/project-8080"
</VirtualHost>

<VirtualHost 172.20.30.40:80>
    ServerName www.mysite-3.org
    DocumentRoot "/www/project-2-80"
</VirtualHost>

<VirtualHost 172.20.30.40:8080>
    ServerName www.mysite-4.org
    DocumentRoot "/www/project-2-8080"
</VirtualHost>
```





> LoadModule

LoadModule is the directive used to inform the Apache server of a module to be loaded. Tons of modules are included in a default Apache installation — and more can be found. But not all modules are loaded by default (nor would you want them to be). If you look in the Apache configuration directory, `/etc/apache2`, for example, you’ll find a subfolder that contains all the available modules. 

In the next lesson, we have explained how to list all the modules, how to install third-party modules, how to enable and how to use them.
 Once you’re sure you want to load a module, do so with the LoadModule directive.

> List available modules:
```
ls /etc/apache2/mods-available/
```

> List Installed Modules:
```
$ apachectl -M
```

> Enable Caching Modules:
```
$ sudo a2enmod cache
$ sudo a2enmod cache_disk
$ sudo a2enmod expires
$ sudo a2enmod headers
```

> KeepAlive

It is an important directive. It defines whether a server allows more than one request per connection. 

Keep Alive is used to prevent clients from consuming too much of the webserver's resources. 
By default, KeepAlive is set to off, which prevents the server from becoming too busy. If you do enable it, use the related KeepAliveTimeout directive and set it to a low number.


Open a terminal and run the following command to open the Apache server configuration file.


```
$ sudo vi /etc/apache2/apache2.conf
```
> Enable Keep-Alive in Apache

```
# KeepAlive: Enable/disable persistent connections
KeepAlive On


# MaxKeepAliveRequests: How many requests to allow during a persistent connection. 
# You can set it 0 for unlimited requests, but it is not recommended.
MaxKeepAliveRequests 100


# KeepAliveTimeout: Number of seconds to wait for the next request from the
# same client on the same connection. Default is 5 seconds
KeepAliveTimeout 15
```

> ServerRoot

The ServerRoot directive sets the directory in which all the webserver's global configurations are defined and set.
Typically it will contain the subdirectories conf/ and logs/. Relative paths in other configuration directives (such as Include or LoadModule, for example) are taken as relative to this directory.
IIn Debian and Ubuntu, it is /etc/apache2 and that’s where all the configuration for virtual hosts, modules, ports, envvars all these configurations lives.

Open the terminal and run the following command to open the Apache server configuration file.


```
$ sudo vi /etc/apache2/apache2.conf
```


```
ServerRoot "/home/httpd"
```


- Logging
The Apache HTTP Server provides a variety of different mechanisms for logging everything that happens on your server, from the initial request, through the URL mapping process, to the final resolution of the connection, including any errors that may have occurred in the process.
The webserver tracks and monitors each and every log that goes in and goes out.
By default, there are two log files
1. access.log and 2. error.log

**Access Log:** This file stores and keep track of logs of information about incoming requests and outgoing responses.Some of the basic information about queries like latency, protocol,client-OS, time-date, HTTP Status, IP address of the client, and more we will cover in this lesson in detail.

**Error Log:** This file contains diagnostic information about any errors that were encountered while processing requests and responses of the active running web application.

ErrorLog, CustomLog: Specifies the location for log files.


To configure log directory:
```
<VirtualHost *:80>
   ErrorLog /your-directory/error.log
   CustomLog /your-directory/access.log combined
</VirtualHost>

```


To display the logs
```
sudo tail -f /var/log/apache2/access.log

```



> DocumentRoot

The DocumentRoot directive specifies where Apache2 should look for the files that are requested by the clients and the files which should be rendered and processed by the webserver. This is the directory from which Apache will read the contents that the visitor will access over the browser. Or in other words, this is the directory that forms the tree of directories that will be accessible over the web.
The "DocumentRoot" option specifies where the content that is requested for this Virtual Host will be located.

The default value is /var/www/html, as specified in /etc/apache2/sites-available/000-default.conf. 

```
<VirtualHost *:80>
        ServerName www.your-domain.com
        ServerAdmin name@your-domain.com
        DocumentRoot /home/web/index.html
        LogLevel warn

        ErrorLog /home/logs/error.log
        CustomLog /home/logs/access.log combined
        #Include conf-available/serve-cgi-bin.conf
</VirtualHost>
```


> Allow From

Apache webserver has this feature to set the configuration of Allow and Deny access to specific IP addresses, hostnames, or groups of addresses and hostnames. The commands are `allow from` and `deny from`



> Allow access from or deny 
Order allow, deny is a setting in your Apache webserver configuration that is used to restrict access to certain directories (folders) or even globally. Configuring who can access your directories is very important for your website security. Order allow, deny is one way to restrict who can see what

The Allow directive affects which hosts "can access" an area of the server. Access is usually controlled by hostname, IP address, or IP address range.

This Deny directive "restricts access" to the server. Restrictions can be based again on hostname, IP address, or environment variables.

The Order directive used in the Order allow, deny directive.

Usage:

```
<Directory "/www">
Order Allow, 
Deny
Deny from all
Allow from all
</Directory>

```

> File Inclusion

Server Side Includes (SSI) concept allows you to configure your webpage or your virtualhost configure to use external files or documents to include in live files and configurations. They are mainly used to serve dynamic content on web pages and reuse HTML codes. When you need to change the navigation bar you change just the include file, not every web page on your server.

```
<VirtualHost *:80>
        ServerName www.your-domain.com
        ServerAdmin name@your-domain.com
        DocumentRoot /home/web/index.html
        LogLevel warn

        ErrorLog /home/logs/error.log
        CustomLog /home/logs/access.log combined
        Include virtual="/header.html"

</VirtualHost>
```

> ENVVARS


ENVAVRS is the configuration file which is located in directory `/etc/apache2/` and it can be set globally or locally. It's an environment variable file for the webserver.
The Apache2 environment variables are set in the `/etc/apache2/envvars` file. These variables are stored and manipulated in an internal Apache structure.

The /etc/apache2/envvars file holds variable definitions such as APACHE_LOG_DIR (the location of Apache log files), APACHE_PID_FILE (the Apache process ID), APACHE_RUN_USERS (the user that runs Apache, by default www-data), etc.


```
vi /etc/apache2/envvars 
OR 
nano /etc/apache2/envvars
```

Add your own variable that will be used in the virtualhost file

```
export MY_API_INSTANCE=127.0.0.1:5000
```

Open virtualhost configuration file of your domain

```
<VirtualHost *:80>
        ServerName www.your-domain.com
        ServerAdmin name@your-domain.com
        DocumentRoot /home/web/index.html
        LogLevel warn

        ErrorLog /home/logs/error.log
        CustomLog /home/logs/access.log combined
        SetEnv FOO_API_INSTANCE ${MY_API_INSTANCE} # our env var
        #Include conf-available/serve-cgi-bin.conf
</VirtualHost>

```


In the Apache web server, the basic building blocks are the Directive upon which developers can lay the project configuration settngs. Getting clean and clear concepts of Directives, modules, configurations, parameters will always save a lot of time debugging the server, scaling it and optimizing according to the developer.