MASTER YOUR
WEB SERVER

// The world's most popular web server.

APACHE2 IS THE BACKBONE OF THE WEB.

Serving over 30% of all websites, Apache HTTP Server is the most widely used web server software. It's free, open-source, and incredibly powerful.

WHY APACHE2?

Apache2 offers unmatched flexibility through its module system, supports all major protocols, and runs on virtually every operating system. The .htaccess feature allows per-directory configuration without access to main config files.

TAKE CONTROL.

Learn to configure, secure, and optimize Apache2. Host multiple websites, enable SSL/TLS, implement rewrite rules, and master the art of web server administration.

BEGIN YOUR JOURNEY →

// The Path to Mastery

12 lessons. Complete Apache2 control.

LESSON 01

Introduction to Apache2

World's most popular web server fundamentals.

Beginner
LESSON 02

Installing Apache2

Install and configure on any Linux distribution.

Beginner
LESSON 03

Configuration Files & Directives

Master httpd.conf and configuration syntax.

Beginner
LESSON 04

Virtual Hosts

Host multiple websites on one server.

Intermediate
LESSON 05

Apache2 Modules

Extend functionality with loadable modules.

Intermediate
LESSON 06

SSL/TLS & HTTPS

Secure sites with Let's Encrypt certificates.

Intermediate
LESSON 07

.htaccess & URL Rewriting

Per-directory config and mod_rewrite rules.

Intermediate
LESSON 08

Authentication & Authorization

Password protection and access control.

Intermediate
LESSON 09

Reverse Proxy Setup

Forward requests to backend applications.

Advanced
LESSON 10

Apache Security

Harden Apache against attacks and exploits.

Advanced
LESSON 11

High Availability

Clustering and failover configurations.

Advanced
LESSON 12

Troubleshooting & Debugging

Fix configuration errors and optimize.

Advanced

// Why Apache2

Apache HTTP Server has been the backbone of the internet since 1995. Its modular architecture, vast ecosystem, and rock-solid stability make it the choice for everything from personal blogs to enterprise deployments.

Unlike proprietary web servers, Apache2 is completely free and open source. You have full access to the source code, can modify it, and distribute your changes. This transparency is essential for security and trust.

Apache2's configuration system is incredibly powerful. With virtual hosts, you can host hundreds of websites on a single server. With mod_rewrite, you have complete control over URLs. With SSL/TLS, you can secure every connection.

The web runs on Apache. Now you can too.

// Tools & References

📖 Official Docs

Apache HTTP Server Documentation

httpd.apache.org/docs

🔧 Apache Utils

Server-side includes, htpasswd, ab

apache.org/utils

🔐 SSL Certificates

Let's Encrypt - Free SSL/TLS

letsencrypt.org

🖥️ Module Reference

All Apache2 modules

apache.org/modules

⚡ Performance Tuning

MPM modules and optimization

apache.org/mpm

🔒 Security Guide

Apache Security Best Practices

apache.org/security

// Introduction to Apache2

×

What is Apache2?

Apache HTTP Server (Apache2) is the world's most widely-used web server software. Originally created in 1995, Apache has been the dominant web server for over two decades. The "2" in Apache2 refers to the major version number, representing a complete rewrite of the original codebase.

Why Apache2?

Apache2 offers several advantages:

  • Open Source: Completely free with full source code access
  • Cross-Platform: Runs on Linux, Windows, macOS, and more
  • Modular: Enable only the features you need
  • Flexible: Extensive configuration options
  • Mature: 30+ years of development and security hardening
MARKET SHARE: Apache2 still serves approximately 30% of all websites worldwide, making it one of the most popular web servers in existence.

Key Apache2 Concepts

  • Modules: Apache2 is modular - enable/disable functionality
  • Virtual Hosts: Host multiple websites on one server
  • .htaccess: Per-directory configuration files
  • MPM: Multi-Processing Modules (how Apache handles requests)
  • Directives: Configuration commands

Checking Apache2 Status

$ apache2 -v Server version: Apache/2.4.52 (Ubuntu) Server built: 2023-03-01T12:00:00
$ systemctl status apache2 ● apache2.service - The Apache HTTP Server Loaded: loaded (/lib/systemd/system/apache2.service; enabled) Active: active (running)

Apache2 File Structure (Ubuntu/Debian)

  • /etc/apache2/ - Main configuration directory
  • /etc/apache2/apache2.conf - Main config file
  • /etc/apache2/sites-available/ - Virtual host configs
  • /etc/apache2/sites-enabled/ - Enabled sites (symlinks)
  • /etc/apache2/mods-available/ - Available modules
  • /var/log/apache2/ - Log files
  • /var/www/html/ - Default document root

Quiz

1. Apache2 was first released in _____.

Hint: Mid-1990s

2. The

Hint: Major version

3. Apache2 is an example of _____ software.

Hint: Free with source code

4. The default document root on Ubuntu is _____.

Hint: Under /var/www

5. Virtual hosts allow hosting _____ websites on one server.

Hint: More than one

6. The main Apache2 configuration file is _____.

Hint: In /etc/apache2/

7. Apache2 uses _____ to enable/disable functionality.

Hint: Like plugins

8. To check Apache2 version, use _____ -v.

Hint: The binary name

Show Answers

Answers

  1. 1995
  2. version number
  3. open source
  4. /var/www/html
  5. multiple
  6. apache2.conf
  7. modules
  8. apache2

// Installing Apache2

×

Installation on Ubuntu/Debian

Installing Apache2 on Debian-based systems is straightforward using apt:

$ sudo apt update Hit:1 http://archive.ubuntu.com/ubuntu jammy InRelease Reading package lists... Done
$ sudo apt install apache2 Reading package lists... Done Building dependency tree... The following NEW packages will be installed: apache2 apache2-bin apache2-data apache2-utils Do you want to continue? [Y/n] y

Installation on CentOS/RHEL/Fedora

On RHEL-based systems, use dnf or yum:

$ sudo dnf install httpd Last metadata expiration check: 0:00:01 ago Package httpd-2.4.52-1.el9.x86_64 is already installed.
NOTE: On CentOS/RHEL, the package is called "httpd" not "apache2". The configuration is also in /etc/httpd/ instead of /etc/apache2/.

Starting and Enabling Apache2

$ sudo systemctl start apache2 # Start Apache2
$ sudo systemctl enable apache2 # Enable on boot
$ sudo systemctl restart apache2 # Restart (after config changes)

Testing Your Installation

After installation, verify Apache2 is serving pages:

$ curl localhost Welcome to Apache2 ...

Or open http://localhost in your browser. You should see the default Apache2 page.

Essential Apache2 Packages

  • apache2 - Main server package
  • apache2-utils - Utility programs (htpasswd, ab, etc.)
  • apache2-bin - Binaries and modules
  • apache2-data - Documentation and default files

Quiz

1. On Ubuntu, Apache2 is installed with the _____ command.

Hint: Uses apt package manager

2. On CentOS, the package is called _____.

Hint: Not apache2

3. To start Apache2 on systemd, use _____.

Hint: systemctl

4. To enable Apache2 on boot, use _____ enable.

Hint: systemctl enable

5. The apache2-utils package contains _____.

Hint: Like htpasswd

6. You can test Apache2 with _____ localhost.

Hint: Command-line HTTP client

7. On RHEL, config files are in _____ instead of /etc/apache2/.

Hint: Different path

8. After config changes, you should _____ Apache2.

Hint: systemctl restart

Show Answers

Answers

  1. apt install apache2
  2. httpd
  3. systemctl start apache2
  4. systemctl
  5. utility programs
  6. curl
  7. /etc/httpd
  8. restart

// Configuration Files & Directives

×

Understanding Apache2 Configuration

Apache2 configuration is organized in a hierarchical structure. Understanding this structure is key to effective server administration.

Main Configuration Files

apache2.conf

The primary configuration file. On Ubuntu/Debian, it's designed to be modular:

ServerRoot "/etc/apache2" ServerName example.com ServerAdmin admin@example.com DocumentRoot "/var/www/html"

Key Directives

ServerRoot

The top-level directory containing configuration files:

ServerRoot "/etc/apache2"

Listen

Specify IP addresses and ports Apache2 listens on:

Listen 80 Listen 443

DocumentRoot

The directory containing web files:

DocumentRoot "/var/www/html" "/var/www/html"> Options Indexes FollowSymLinks AllowOverride None Require all granted

Directory Configuration

The block controls access to specific directories:

"/var/www"> Options Indexes FollowSymLinks AllowOverride None Require all granted

Testing Configuration

Always test configuration before restarting:

$ sudo apache2ctl configtest Syntax OK
IMPORTANT: A syntax error in Apache2 configuration can prevent the server from starting. Always test with apache2ctl configtest first.

Configuration Include Files

Apache2 uses Include directives to load additional configuration:

IncludeOptional mods-enabled/*.load IncludeOptional mods-enabled/*.conf Include ports.conf IncludeOptional conf-enabled/*.conf IncludeOptional sites-enabled/*.conf

Quiz

1. The main Apache2 configuration file is _____.

Hint: In /etc/apache2/

2. The _____ directive specifies the web root directory.

Hint: Where files are served from

3. To specify which ports Apache listens on, use _____.

Hint: Listen 80

4. The _____ block controls access to directories.

Hint: XML-like tag

5. To test config syntax, use _____.

Hint: apache2ctl

6. On RHEL, Apache2 config is in _____ directory.

Hint: Different from Debian

7. The ServerAdmin directive sets the _____ email.

Hint: For error pages

8. Include directives load additional _____ files.

Hint: Config files

Show Answers

Answers

  1. apache2.conf
  2. DocumentRoot
  3. Listen
  4. apache2ctl configtest
  5. /etc/httpd
  6. administrator
  7. configuration

// Virtual Hosts

×

What are Virtual Hosts?

Virtual hosts allow Apache2 to serve multiple websites from a single server. This is essential for web hosting and development.

Types of Virtual Hosts

  • Name-based: Multiple domains, one IP (most common)
  • IP-based: Different IP per website
  • Port-based: Different port per website

Creating a Name-based Virtual Host

Create a configuration file in /etc/apache2/sites-available/:

ServerName example.com ServerAlias www.example.com DocumentRoot "/var/www/example.com" "/var/www/example.com"> Options -Indexes +FollowSymLinks AllowOverride All Require all granted ErrorLog \${APACHE_LOG_DIR}/example.com-error.log CustomLog \${APACHE_LOG_DIR}/example.com-access.log combined

Enabling Sites

$ sudo a2ensite example.com.conf Enabling site example.com. To activate the new configuration, you need to run: service apache2 reload
$ sudo a2dissite example.com.conf # Disable a site

Default Virtual Host

The default site serves requests that don't match any ServerName:

$ ls /etc/apache2/sites-enabled/ 000-default.conf default-ssl.conf

Multiple Sites on Same Server

You can have multiple virtual hosts:

$ ls /etc/apache2/sites-available/ example.com.conf blog.example.com.conf api.example.com.conf 000-default.conf default-ssl.conf

Virtual Host with Different Ports

ServerName internal.example.com DocumentRoot "/var/www/internal"

Make sure Listen 8080 is in ports.conf:

Listen 8080

Restarting Apache2

$ sudo systemctl reload apache2 # Graceful reload (serves existing requests)
$ sudo systemctl restart apache2 # Full restart (interrupts active connections)

Quiz

1. _____ virtual hosts use one IP for multiple domains.

Hint: Most common type

2. To enable a site, use _____.

Hint: Apache2 enable site

3. To disable a site, use _____.

Hint: Apache2 disable site

4. The ServerAlias directive creates _____ names for a site.

Hint: Additional domain names

5. Virtual host configs are in _____ directory.

Hint: Available sites

6. To listen on port 8080, add _____ 8080.

Hint: In ports.conf

7. _____ reload gracefully updates the config.

Hint: Without interrupting

8. The default site serves requests matching no _____.

Hint: Domain name

Show Answers

Answers

  1. name-based
  2. a2ensite
  3. a2dissite
  4. alternative
  5. /etc/apache2/sites-available
  6. Listen
  7. systemctl reload apache2
  8. ServerName

// Apache2 Modules

×

Apache2 Module System

One of Apache2's greatest strengths is its modular architecture. Modules can be enabled or disabled to add or remove functionality.

Commonly Used Core Modules

  • mod_ssl - SSL/TLS support
  • mod_rewrite - URL rewriting
  • mod_proxy - Proxying functionality
  • mod_auth_basic - Basic authentication
  • mod_headers - Custom HTTP headers
  • mod_expires - Cache control headers
  • mod_compress - Gzip compression

Listing Enabled Modules

$ apache2ctl -M Loaded Modules: core_module (static) log_config_module (static) logio_module (static) mpm_prefork_module (static) authz_core_module (static) ... rewrite_module (shared) ssl_module (shared)

Enabling Modules

$ sudo a2enmod rewrite Enabling module rewrite. To activate the new configuration, you need to run: service apache2 reload
$ sudo a2enmod ssl Enabling module ssl. To activate the new configuration, you need to run: service apache2 reload

Disabling Modules

$ sudo a2dismod rewrite # Disable a module

Checking Available Modules

$ ls /etc/apache2/mods-available/ access_compat.load autoindex.load deflate.load alias.load authn_file.load dir.load ...

Module Configuration

Some modules have their own configuration files:

$ ls /etc/apache2/mods-enabled/ access_compat.load authz_host.load dir.load alias.conf authz_user.load mime.load ...

Loading External Modules

Load external modules using LoadDirective:

LoadModule php_module /usr/lib/apache2/modules/libphp.so

MPM (Multi-Processing Modules)

MPMs handle how Apache2 accepts and handles connections:

  • prefork - One process per request (compatible)
  • worker - Multiple threads per process
  • event - Async, best for keep-alive
$ sudo a2dismod mpm_prefork && sudo a2enmod mpm_event # Switch from prefork to event MPM
NOTE: If using PHP, you must use prefork MPM. Threaded MPMs require thread-safe PHP (php-fpm).

Quiz

1. To enable a module, use _____.

Hint: Apache2 enable module

2. To list loaded modules, use _____.

Hint: List modules

3. mod_rewrite provides _____ rewriting.

Hint: Clean URLs

4. mod_ssl provides _____ support.

Hint: HTTPS

5. The _____ MPM uses threads for connections.

Hint: Threaded MPM

6. PHP requires the _____ MPM.

Hint: Non-threaded

7. To disable a module, use _____.

Hint: Apache2 disable module

8. Modules are stored in _____ directory.

Hint: Available modules

Show Answers

Answers

  1. a2enmod
  2. apache2ctl -M
  3. URL
  4. SSL/TLS
  5. worker
  6. prefork
  7. a2dismod
  8. /etc/apache2/mods-available

// SSL/TLS & HTTPS

×

Why SSL/TLS?

SSL/TLS encrypts communication between the server and clients, protecting sensitive data from interception. It's essential for security and SEO.

SSL Certificate Types

  • DV (Domain Validation): Basic, verifies domain ownership
  • OV (Organization Validation): Verifies organization identity
  • EV (Extended Validation): Highest trust, green bar
  • Self-signed: For testing only, not trusted by browsers

Enabling SSL Module

$ sudo a2enmod ssl

Creating Self-Signed Certificate (Testing)

$ sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/ssl/private/apache-selfsigned.key -out /etc/ssl/certs/apache-selfsigned.crt Generating a 2048 bit RSA private key .......................+++ ....+++ writing new private key to '/etc/ssl/private/apache-selfsigned.key'

Creating SSL Virtual Host

ServerName example.com DocumentRoot "/var/www/html" SSLEngine on SSLCertificateFile /etc/ssl/certs/apache-selfsigned.crt SSLCertificateKeyFile /etc/ssl/private/apache-selfsigned.key "/var/www/html"> Options -Indexes +FollowSymLinks AllowOverride All Require all granted

SSL Configuration Options

SSLProtocol all -SSLv3 -TLSv1 -TLSv1.1 SSLCipherSuite ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512 SSLHonorCipherOrder on SSLCompression off SSLOpenSSLConfCmd ECDHEParameters secp521r1 SSLOpenSSLConfCmd CipherSuites ECDHE-RSA-AES256-GCM-SHA384

Forcing HTTPS

Redirect all HTTP traffic to HTTPS:

ServerName example.com Redirect permanent / https://example.com/

Using Let's Encrypt (Production)

$ sudo apt install certbot python3-certbot-apache
$ sudo certbot --apache -d example.com -d www.example.com Saving debug log to /var/log/letsencrypt/letsencrypt.log Successfully received certificate. Certificate is saved at: /etc/letsencrypt/live/example.com/fullchain.pem Key is saved at: /etc/letsencrypt/live/example.com/privkey.pem

Testing SSL Configuration

$ openssl s_client -connect example.com:443 CONNECTED(00000003) ... SSL-Session: Protocol : TLSv1.3 Cipher : TLS_AES_256_GCM_SHA384

Quiz

1. _____ encrypts communication between server and client.

Hint: HTTPS

2. To enable SSL, use _____.

Hint: Enable SSL module

3. Let

Hint: DV certificates

4. The SSLCertificateFile directive specifies the _____.

Hint: Public key file

5. The SSLCertificateKeyFile directive specifies the _____.

Hint: Secret key file

6. To redirect HTTP to HTTPS, use _____ directive.

Hint: Permanent redirect

7. Self-signed certificates are for _____ only.

Hint: Not production

8. certbot is used to obtain _____ certificates.

Hint: From Let

Show Answers

Answers

  1. SSL/TLS
  2. a2enmod ssl
  3. free
  4. certificate
  5. private key
  6. Redirect
  7. testing
  8. SSL/TLS

// .htaccess & URL Rewriting

×

What is .htaccess?

The .htaccess file allows per-directory configuration without access to the main server configuration. It's incredibly powerful for shared hosting and per-site customization.

Enabling .htaccess

First, enable AllowOverride in your virtual host:

"/var/www/html"> Options Indexes FollowSymLinks AllowOverride All Require all granted

AllowOverride Options

  • None: Disable .htaccess
  • All: Enable all directives
  • AuthConfig: Allow auth directives
  • FileInfo: Allow rewrite directives
  • Indexes: Allow directory indexing
  • Limit: Allow access control

Password Protection

Create a password file:

$ htpasswd -c /etc/apache2/.htpasswd username New password: Re-type new password: Adding password for user username

Create .htaccess:

AuthType Basic AuthName "Restricted Area" AuthUserFile /etc/apache2/.htpasswd Require valid-user

mod_rewrite Basics

Enable mod_rewrite first:

$ sudo a2enmod rewrite

Simple Redirects

RewriteEngine On RewriteRule ^oldpage\.html$ /newpage.html [R=301,L]

Clean URLs

Convert /article.php?id=123 to /article/123:

RewriteEngine On RewriteRule ^article/([0-9]+)$ /article.php?id=$1 [L]

Forcing HTTPS

RewriteEngine On RewriteCond %{HTTPS} off RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Blocking IP Addresses

Order deny,allow Deny from 192.168.1.100 Deny from 10.0.0.0/8

Custom Error Pages

ErrorDocument 404 /errors/404.html ErrorDocument 403 /errors/403.html ErrorDocument 500 /errors/500.html

Directory Index

DirectoryIndex index.php index.html Options -Indexes

Quiz

1. The .htaccess file allows _____ configuration.

Hint: Without main config

2. To enable .htaccess, set AllowOverride to _____.

Hint: Allow all directives

3. htpasswd creates a _____ file.

Hint: For authentication

4. mod_rewrite provides _____ rewriting.

Hint: Clean URLs

5. The R=301 flag means _____ redirect.

Hint: HTTP 301

6. The [L] flag means _____ rule.

Hint: Last rule, stop processing

7. ErrorDocument handles _____ pages.

Hint: 404, 500, etc.

8. To block an IP, use _____ from.

Hint: Deny from IP

Show Answers

Answers

  1. per-directory
  2. All
  3. password
  4. URL
  5. permanent
  6. last
  7. error
  8. Deny

// Authentication & Authorization

×

Apache Authentication Methods

Apache2 provides multiple authentication mechanisms to protect your web resources. Understanding these methods is essential for securing sensitive content.

Basic Authentication

The simplest form of authentication. Credentials are sent base64-encoded (not encrypted) and should only be used with HTTPS:

AuthType Basic AuthName "Restricted Area" AuthUserFile /etc/apache2/.htpasswd Require valid-user

Creating Password Files

$ sudo htpasswd -c /etc/apache2/.htpasswd admin New password: Re-type new password: Adding password for user admin
$ sudo htpasswd /etc/apache2/.htpasswd user2 # Add another user (without -c flag)

Digest Authentication

More secure than Basic auth as passwords are never sent over the network:

$ sudo a2enmod auth_digest
AuthType Digest AuthName "Private Area" AuthDigestProvider file AuthUserFile /etc/apache2/.htdigest Require valid-user
$ sudo htdigest -c /etc/apache2/.htdigest "Private Area" admin
SECURITY NOTE: Always use HTTPS with Basic authentication. Without SSL/TLS, credentials are sent in base64 which is easily decoded.

LDAP Integration

Authenticate against an LDAP directory server:

$ sudo a2enmod authnz_ldap
AuthType Basic AuthName "LDAP Authentication" AuthBasicProvider ldap AuthLDAPURL "ldap://ldap.example.com/ou=People,dc=example,dc=com?uid" AuthLDAPBindDN "cn=apache,dc=example,dc=com" AuthLDAPBindPassword "secret" Require valid-user

.htaccess Authentication

Place authentication directives in .htaccess for per-directory protection:

$ cat /var/www/html/admin/.htaccess AuthType Basic AuthName "Admin Panel" AuthUserFile /etc/apache2/.htpasswd Require user admin

Access Control by IP

Require ip 192.168.1.0/24
Require host example.com

Combining Requirements

Require valid-user Require ip 10.0.0.0/8

Group-Based Authorization

AuthGroupFile /etc/apache2/.htgroup Require group admins
$ cat /etc/apache2/.htgroup admins: admin user1 user2 users: user3 user4 user5

Quiz

1. Basic auth sends credentials _____ encoded.

Hint: Not encrypted

2. _____ authentication never sends passwords over the network.

Hint: Uses MD5 hash

3. Use _____ to create password files for Basic auth.

Hint: Apache utility

4. _____ integrates Apache with directory servers.

Hint: Lightweight Directory

5. Require _____ grants access to valid users only.

Hint: Any valid user

6. _____ files allow per-directory auth config.

Hint: Distributed config

7. Require _____ 192.168.1.0/24 allows that subnet.

Hint: IP-based access

8. AuthGroupFile defines user _____ for authorization.

Hint: User collections

Show Answers

Answers

  1. base64
  2. digest
  3. htpasswd
  4. LDAP
  5. valid-user
  6. .htaccess
  7. ip
  8. groups

// Reverse Proxy Setup

×

What is a Reverse Proxy?

A reverse proxy sits between clients and backend servers, forwarding client requests to the appropriate backend. It's essential for load balancing, SSL termination, and application delivery.

Enabling Proxy Modules

$ sudo a2enmod proxy
$ sudo a2enmod proxy_http
$ sudo a2enmod proxy_balancer
$ sudo a2enmod lbmethod_byrequests

Basic Reverse Proxy

ProxyPreserveHost On ProxyPass / http://localhost:3000/ ProxyPassReverse / http://localhost:3000/
IMPORTANT: ProxyPreserveHost preserves the original Host header, essential for virtual host routing on the backend.

Proxy with Path Mapping

ProxyPass /api http://backend.local:8080/api ProxyPassReverse /api http://backend.local:8080/api

Load Balancing Backend Servers

BalancerMember http://backend1:8080 loadfactor=3 BalancerMember http://backend2:8080 loadfactor=2 BalancerMember http://backend3:8080 status=+H ProxyPass /app balancer://mycluster/ ProxyPassReverse /app balancer://mycluster/

Load Balancer Methods

  • byrequests: Request counting (default)
  • bytraffic: Traffic bytes balancing
  • bybusyness: Based on current requests
  • heartbeat: Heartbeat monitoring

WebSocket Proxy

Enable WebSocket support for real-time applications:

$ sudo a2enmod proxy_wstunnel
ProxyPass /ws ws://backend.local:8080/ws ProxyPassReverse /ws ws://backend.local:8080/ws
RewriteEngine On RewriteCond %{HTTP:Upgrade} websocket [NC] RewriteCond %{HTTP:Connection} upgrade [NC] RewriteRule ^/ws(.*)$ "ws://backend.local:8080/ws$1" [P,L]

Proxy with SSL Termination

ServerName api.example.com SSLEngine On SSLCertificateFile /etc/ssl/certs/api.crt SSLCertificateKeyFile /etc/ssl/private/api.key ProxyPass / http://internal-backend:8080/ ProxyPassReverse / http://internal-backend:8080/

Proxy Timeouts and Retry

ProxyTimeout 600 ProxyBadHeader Ignore ProxyErrorOverride On

Health Checks

BalancerMember http://web1:80 hcmethod=GET hcuri=/health hcinterval=10 BalancerMember http://web2:80 hcmethod=GET hcuri=/health hcinterval=10

Quiz

1. ProxyPass forwards requests to _____ servers.

Hint: Upstream servers

2. _____ preserves the original Host header.

Hint: Keep original host

3. BalancerMember defines _____ in a cluster.

Hint: Pool members

4. mod_proxy_ enables WebSocket proxy support.

Hint: WS tunnel module

5. _____ handles SSL at the proxy level.

Hint: SSL offloading

6. loadfactor controls the _____ of traffic.

Hint: Traffic split

7. _____ monitors backend server health.

Hint: hcmethod/hcuri

8. status=+H marks a server as _____.

Hint: Standby mode

Show Answers

Answers

  1. backend
  2. ProxyPreserveHost
  3. backend servers
  4. wstunnel
  5. SSL termination
  6. distribution
  7. health checks
  8. hot standby

// Apache Security

×

Web Application Firewall (ModSecurity)

ModSecurity is an open-source WAF that protects against SQL injection, XSS, and other attacks. It provides real-time monitoring and blocking.

$ sudo apt install libapache2-mod-security2
$ sudo a2enmod security2

Basic ModSecurity Configuration

SecRuleEngine On SecRequestBodyAccess On SecRequestBodyLimit 13107200 SecResponseBodyAccess On SecResponseBodyLimit 524288

OWASP Core Rule Set

$ sudo apt install modsecurity-crs
WAF PROTECTION: The OWASP CRS protects against the OWASP Top 10 vulnerabilities including SQL injection, XSS, CSRF, and more.

Security Headers

Enable mod_headers to add security headers:

$ sudo a2enmod headers
Header always set X-Frame-Options "SAMEORIGIN" Header always set X-Content-Type-Options "nosniff" Header always set X-XSS-Protection "1; mode=block" Header always set Referrer-Policy "strict-origin-when-cross-origin"

Content Security Policy (CSP)

CSP prevents XSS by controlling which resources can load:

Header always set Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self'; media-src 'self'; object-src 'none'; frame-ancestors 'self'; base-uri 'self'; form-action 'self'"

Rate Limiting

$ sudo a2enmod reqtimeout
RequestReadTimeout header=20-40,MinRate=500 body=20,MinRate=500

DDoS Protection with mod_evasive

$ sudo apt install libapache2-mod-evasive
DOSHashTableSize 3097 DOSPageCount 2 DOSSiteCount 50 DOSPageInterval 1 DOSSiteInterval 1 DOSBlockingPeriod 10 DOSEmailNotify admin@example.com DOSLogDir "/var/log/mod_evasive"

Hide Server Information

ServerTokens Prod ServerSignature Off

Disable Unnecessary Methods

AllowMethods GET POST HEAD OPTIONS

Strict Transport Security (HSTS)

Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"

Quiz

1. ModSecurity is a _____ firewall.

Hint: WAF

2. _____ prevents clickjacking attacks.

Hint: Frame control

3. CSP stands for Content _____ Policy.

Hint: Security policy

4. mod_ provides DDoS protection.

Hint: Evasive

5. _____ hides Apache version info.

Hint: Server tokens

6. HSTS enforces _____ connections.

Hint: Secure transport

7. _____ prevents MIME type sniffing.

Hint: Content type header

8. CRS stands for Core Rule _____.

Hint: Rule collection

Show Answers

Answers

  1. Web application
  2. X-Frame-Options
  3. Security
  4. evasive
  5. ServerTokens
  6. HTTPS
  7. X-Content-Type-Options
  8. Set

// High Availability

×

Apache High Availability Architecture

High availability ensures your web services remain accessible even during server failures. This involves multiple Apache instances, load balancing, and session persistence.

Multiple Apache Instances

Run multiple Apache instances on different ports or servers:

# Instance 1 - Port 80 Listen 80 ServerName web1.example.com # Instance 2 - Port 8080 Listen 8080 ServerName web2.example.com

Session Sharing with Memcached

$ sudo apt install memcached libapache2-mod-session-memcached
$ sudo a2enmod session session_cookie session_memcached
Session On SessionCookieName session path=/ SessionMemcachedServers memcached.example.com:11211 SessionMemcachedPrefix apache_session_ SessionMaxAge 3600

Session Sharing with Redis

$ sudo apt install libapache2-mod-session-redis
Session On SessionCookieName session path=/ SessionRedisHost redis.example.com SessionRedisPort 6379 SessionRedisPrefix apache_session_
SESSION PERSISTENCE: Shared sessions allow users to maintain login state across multiple Apache servers, essential for horizontal scaling.

Cluster Configuration with mod_proxy_balancer

BalancerMember http://apache1:80 route=node1 BalancerMember http://apache2:80 route=node2 BalancerMember http://apache3:80 route=node3 ProxySet stickysession=session|jsessionid ProxySet lbmethod=byrequests ProxyPass / balancer://cluster/ ProxyPassReverse / balancer://cluster/

Sticky Sessions

Header add Set-Cookie "session=.%{BALANCER_WORKER_ROUTE}e; path=/; HttpOnly; Secure" env=BALANCER_ROUTE_CHANGED

Active-Passive Failover

BalancerMember http://primary:80 BalancerMember http://backup:80 status=+H

Health Check Configuration

ProxyHCExpr is_up {%{REMOTE_ADDR} =~ /127\.0\.0\.1/} ProxyHCTemplate check method=GET uri=/health.html interval=5 timeout=2 BalancerMember http://server1:80 hctemplate=check BalancerMember http://server2:80 hctemplate=check

HAProxy Alternative Setup

External load balancer in front of Apache cluster:

# haproxy.cfg frontend web_frontend bind *:80 default_backend apache_backend backend apache_backend balance roundrobin cookie SESSION insert indirect nocache server apache1 192.168.1.10:80 check cookie node1 server apache2 192.168.1.11:80 check cookie node2

Quiz

1. Multiple Apache instances run on different _____.

Hint: Network ports

2. _____ stores session data in memory cache.

Hint: Memory cache daemon

3. _____ provides in-memory data structure store.

Hint: Remote dictionary server

4. Sticky _____ keeps users on the same server.

Hint: Session affinity

5. status=+H marks a server as _____.

Hint: Backup server

6. _____ checks monitor server health.

Hint: Health checks

7. A cluster of servers provides _____ availability.

Hint: HA

8. _____ insert adds session cookies.

Hint: Cookie directive

Show Answers

Answers

  1. ports
  2. Memcached
  3. Redis
  4. sessions
  5. hot standby
  6. health
  7. high
  8. cookie

// Troubleshooting & Debugging

×

Systematic Troubleshooting

When Apache2 fails or behaves unexpectedly, a systematic approach saves time. This lesson covers diagnostic tools and common issues.

Error Logs

The first place to check when something goes wrong:

$ sudo tail -f /var/log/apache2/error.log [Wed Jan 15 10:30:45.123456 2025] [mpm_prefork:error] [pid 1234] AH00161: server reached MaxRequestWorkers setting

Log Levels

Increase verbosity for detailed debugging:

LogLevel debug
LogLevel info ssl:warn rewrite:trace8

Access Pattern Analysis

$ awk '{print $9}' /var/log/apache2/access.log | sort | uniq -c | sort -rn 5432 200 234 404 56 500 12 403
$ awk '{print $1}' /var/log/apache2/access.log | sort | uniq -c | sort -rn | head -10 # Top 10 client IPs
LOG ANALYSIS: Use awk, grep, and sort to extract insights from access logs. Look for error patterns, traffic spikes, and suspicious activity.

Common Issues and Solutions

Permission Denied Errors

$ sudo ls -la /var/www/html/ # Check file ownership
$ sudo chmod -R 755 /var/www/html $ sudo chown -R www-data:www-data /var/www/html

Port Already in Use

$ sudo lsof -i :80 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME nginx 1234 root 6u IPv4 12345 0t0 TCP *:http (LISTEN)

Configuration Syntax Errors

$ sudo apache2ctl configtest AH00526: Syntax error on line 10 of /etc/apache2/sites-enabled/example.conf: Invalid command 'SSLEngine', perhaps misspelled or defined by a module not included in the server configuration

Debugging Modules

$ sudo a2enmod dumpio # Log request/response bodies
DumpIOInput On DumpIOOutput On LogLevel dumpio:trace7

Rewrite Rule Debugging

LogLevel rewrite:trace8
$ sudo tail -f /var/log/apache2/error.log | grep rewrite

Using strace

Trace system calls for deep debugging:

$ sudo strace -p $(pgrep -o apache2) -e trace=file 2>&1 | grep -E "open|stat|access"
$ sudo strace -f -e trace=network -p $(pgrep -o apache2) 2>&1 # Trace network operations

Debug Mode

$ sudo apache2 -X # Run in foreground (single process, debug mode)

Module Loading Verification

$ apache2ctl -M 2>&1 | grep ssl ssl_module (shared)

Checking Virtual Host Configuration

$ sudo apache2ctl -S VirtualHost configuration: *:80 is a NameVirtualHost default server example.com (/etc/apache2/sites-enabled/000-default.conf:1) port 80 namevhost example.com (/etc/apache2/sites-enabled/000-default.conf:1)

Quiz

1. _____ logs contain detailed error information.

Hint: error.log

2. _____ analyzes access log patterns.

Hint: Text processing

3. Permission denied means check file _____.

Hint: chown/chmod

4. mod_dumpio logs request and response _____.

Hint: Full content

5. _____ traces system calls.

Hint: System trace

6. apache2ctl -X runs in _____ mode.

Hint: Foreground mode

7. _____ configtest checks syntax.

Hint: Apache control

8. _____ -S shows virtual host config.

Hint: Apache control

Show Answers

Answers

  1. error
  2. awk
  3. ownership
  4. bodies
  5. strace
  6. debug
  7. apache2ctl
  8. apache2ctl