Apache HTTP Server: Complete Guide and Documentation

Comprehensive guide to Apache HTTP Server covering installation, configuration, virtual hosts, security, SSL/TLS, performance optimization, and troubleshooting.

Apache HTTP Server: Complete Guide and Documentation

Table of Contents

1. [Introduction](#introduction) 2. [Installation](#installation) 3. [Configuration](#configuration) 4. [Virtual Hosts](#virtual-hosts) 5. [Security](#security) 6. [Performance Optimization](#performance-optimization) 7. [Modules](#modules) 8. [Log Management](#log-management) 9. [SSL/TLS Configuration](#ssltls-configuration) 10. [Troubleshooting](#troubleshooting) 11. [Commands Reference](#commands-reference)

Introduction

Apache HTTP Server, commonly referred to as Apache, is one of the most widely used web servers in the world. Developed by the Apache Software Foundation, it is an open-source, cross-platform web server that has been serving web content since 1995. Apache is known for its flexibility, reliability, and extensive feature set.

Key Features

| Feature | Description | |---------|-------------| | Cross-platform | Runs on Unix, Linux, Windows, and macOS | | Modular Architecture | Extensible through modules | | Virtual Hosting | Multiple websites on single server | | URL Rewriting | Powerful URL manipulation | | SSL/TLS Support | Secure connections | | Authentication | Multiple authentication methods | | Compression | Content compression support | | Load Balancing | Distribution of requests |

Apache Architecture

Apache follows a modular architecture where core functionality is extended through modules. The server consists of:

- Core: Basic HTTP functionality - Multi-Processing Modules (MPMs): Handle connection processing - Standard Modules: Common functionality like authentication, SSL - Third-party Modules: Extended functionality

Installation

Linux (Ubuntu/Debian)

`bash

Update package repository

sudo apt update

Install Apache

sudo apt install apache2

Start Apache service

sudo systemctl start apache2

Enable Apache to start on boot

sudo systemctl enable apache2

Check Apache status

sudo systemctl status apache2 `

Linux (CentOS/RHEL/Fedora)

`bash

Install Apache (httpd package)

sudo yum install httpd

or for newer versions

sudo dnf install httpd

Start Apache service

sudo systemctl start httpd

Enable Apache to start on boot

sudo systemctl enable httpd

Check Apache status

sudo systemctl status httpd `

Windows

1. Download Apache from Apache Lounge or official Apache website 2. Extract files to desired directory (e.g., C:\Apache24) 3. Install as Windows service:

`cmd

Navigate to Apache bin directory

cd C:\Apache24\bin

Install Apache as service

httpd.exe -k install

Start Apache service

httpd.exe -k start `

macOS

`bash

Using Homebrew

brew install httpd

Start Apache

sudo brew services start httpd `

Post-Installation Verification

After installation, verify Apache is running by accessing http://localhost in your browser. You should see the Apache default page.

Configuration

Apache configuration is managed through configuration files, with the main configuration file typically located at:

| Operating System | Main Config File | |------------------|------------------| | Ubuntu/Debian | /etc/apache2/apache2.conf | | CentOS/RHEL | /etc/httpd/conf/httpd.conf | | Windows | C:\Apache24\conf\httpd.conf | | macOS | /usr/local/etc/httpd/httpd.conf |

Main Configuration Directives

#### Server Root and Document Root

`apache

Server root directory

ServerRoot "/etc/apache2"

Document root - where web files are served from

DocumentRoot "/var/www/html"

Directory permissions for document root

Options Indexes FollowSymLinks AllowOverride None Require all granted `

#### Listen Directive

`apache

Listen on port 80 for all interfaces

Listen 80

Listen on specific IP and port

Listen 192.168.1.100:80

Listen on port 443 for SSL

Listen 443 ssl `

#### Server Information

`apache

Server administrator email

ServerAdmin webmaster@example.com

Server name (FQDN)

ServerName www.example.com:80

Server tokens (security consideration)

ServerTokens Prod ServerSignature Off `

Directory Configuration

Directory blocks control access and behavior for specific directories:

`apache # Options for this directory Options Indexes FollowSymLinks MultiViews # Allow .htaccess overrides AllowOverride All # Access control Require all granted # Index files DirectoryIndex index.html index.php `

#### Options Directive Values

| Option | Description | |--------|-------------| | Indexes | Allow directory browsing | | FollowSymLinks | Follow symbolic links | | ExecCGI | Allow CGI execution | | Includes | Allow server-side includes | | MultiViews | Allow content negotiation | | None | No options enabled | | All | All options enabled |

#### AllowOverride Values

| Value | Description | |-------|-------------| | None | No .htaccess overrides allowed | | All | All overrides allowed | | AuthConfig | Authorization directives | | FileInfo | Document type directives | | Indexes | Directory indexing directives | | Limit | Access control directives |

Virtual Hosts

Virtual hosts allow Apache to serve multiple websites from a single server. There are two types:

Name-based Virtual Hosts

Multiple domains sharing the same IP address:

`apache

Enable name-based virtual hosting

NameVirtualHost *:80

First virtual host

ServerName www.example1.com ServerAlias example1.com DocumentRoot "/var/www/example1" ErrorLog "/var/log/apache2/example1_error.log" CustomLog "/var/log/apache2/example1_access.log" combined Options -Indexes +FollowSymLinks AllowOverride All Require all granted

Second virtual host

ServerName www.example2.com ServerAlias example2.com DocumentRoot "/var/www/example2" ErrorLog "/var/log/apache2/example2_error.log" CustomLog "/var/log/apache2/example2_access.log" combined Options -Indexes +FollowSymLinks AllowOverride All Require all granted `

IP-based Virtual Hosts

Different IP addresses for different sites:

`apache ServerName www.example1.com DocumentRoot "/var/www/example1"

ServerName www.example2.com DocumentRoot "/var/www/example2" `

Virtual Host Best Practices

1. Create separate configuration files for each virtual host 2. Use descriptive log file names for easier troubleshooting 3. Set appropriate directory permissions 4. Include error pages for better user experience 5. Configure SSL for production sites

`apache

Example comprehensive virtual host

ServerName www.mysite.com ServerAlias mysite.com DocumentRoot "/var/www/mysite" # Logging ErrorLog "/var/log/apache2/mysite_error.log" CustomLog "/var/log/apache2/mysite_access.log" combined LogLevel warn # Directory configuration Options -Indexes +FollowSymLinks +MultiViews AllowOverride All Require all granted # Error pages ErrorDocument 404 /errors/404.html ErrorDocument 500 /errors/500.html # Security headers Header always set X-Frame-Options DENY Header always set X-Content-Type-Options nosniff `

Security

Basic Security Configuration

`apache

Hide Apache version

ServerTokens Prod ServerSignature Off

Disable server-info and server-status

Require all denied

Require all denied

Prevent access to .htaccess files

Require all denied

Disable directory browsing globally

Options -Indexes

Prevent access to sensitive files

Require all denied `

Authentication and Authorization

#### Basic Authentication

`apache

Create password file

htpasswd -c /etc/apache2/.htpasswd username

Configure authentication

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

#### IP-based Access Control

`apache

Allow specific IP addresses

Require ip 192.168.1.0/24 Require ip 10.0.0.1

Deny specific IP addresses

Require all granted Require not ip 192.168.1.100 `

Security Headers

`apache

Load headers module

LoadModule headers_module modules/mod_headers.so

Security 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" Header always set Permissions-Policy "geolocation=(), microphone=(), camera=()"

HSTS (HTTP Strict Transport Security)

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

Performance Optimization

Multi-Processing Modules (MPMs)

Apache offers different MPMs for handling requests:

| MPM | Description | Best For | |-----|-------------|----------| | prefork | Process-based, one thread per process | PHP applications, maximum compatibility | | worker | Hybrid process/thread model | High-traffic sites with thread-safe applications | | event | Enhanced worker with better keep-alive handling | High-traffic sites, static content |

#### Prefork Configuration

`apache StartServers 8 MinSpareServers 5 MaxSpareServers 20 MaxRequestWorkers 256 MaxConnectionsPerChild 0 `

#### Worker Configuration

`apache StartServers 3 MinSpareThreads 75 MaxSpareThreads 250 ThreadsPerChild 25 MaxRequestWorkers 400 MaxConnectionsPerChild 0 `

#### Event Configuration

`apache StartServers 3 MinSpareThreads 75 MaxSpareThreads 250 ThreadsPerChild 25 MaxRequestWorkers 400 MaxConnectionsPerChild 0 AsyncRequestWorkerFactor 2 `

Compression

Enable compression to reduce bandwidth usage:

`apache

Load compression modules

LoadModule deflate_module modules/mod_deflate.so

Configure compression

SetOutputFilter DEFLATE SetEnvIfNoCase Request_URI \ \.(?:gif|jpe?g|png)$ no-gzip dont-vary SetEnvIfNoCase Request_URI \ \.(?:exe|t?gz|zip|bz2|sit|rar)$ no-gzip dont-vary SetEnvIfNoCase Request_URI \ \.pdf$ no-gzip dont-vary

Alternative configuration

AddOutputFilterByType DEFLATE text/plain AddOutputFilterByType DEFLATE text/html AddOutputFilterByType DEFLATE text/xml AddOutputFilterByType DEFLATE text/css AddOutputFilterByType DEFLATE application/xml AddOutputFilterByType DEFLATE application/xhtml+xml AddOutputFilterByType DEFLATE application/rss+xml AddOutputFilterByType DEFLATE application/javascript AddOutputFilterByType DEFLATE application/x-javascript `

Caching

#### Browser Caching

`apache

Load expires module

LoadModule expires_module modules/mod_expires.so

Enable expires

ExpiresActive On

Set default expiration

ExpiresDefault "access plus 1 month"

Specific file types

ExpiresByType text/css "access plus 1 year" ExpiresByType application/javascript "access plus 1 year" ExpiresByType image/png "access plus 1 year" ExpiresByType image/jpg "access plus 1 year" ExpiresByType image/jpeg "access plus 1 year" ExpiresByType image/gif "access plus 1 year" ExpiresByType image/ico "access plus 1 year" ExpiresByType image/icon "access plus 1 year" ExpiresByType text/html "access plus 1 day" `

#### Cache Control Headers

`apache # Cache static assets Header set Cache-Control "max-age=31536000, public" # Don't cache HTML files Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate" Header set Pragma "no-cache" Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT" `

Modules

Loading Modules

`apache

Load module

LoadModule rewrite_module modules/mod_rewrite.so

Check if module is loaded

# Module-specific configuration `

Essential Modules

| Module | Purpose | Configuration | |--------|---------|---------------| | mod_rewrite | URL rewriting | LoadModule rewrite_module modules/mod_rewrite.so | | mod_ssl | SSL/TLS support | LoadModule ssl_module modules/mod_ssl.so | | mod_headers | HTTP headers | LoadModule headers_module modules/mod_headers.so | | mod_deflate | Compression | LoadModule deflate_module modules/mod_deflate.so | | mod_expires | Expiration headers | LoadModule expires_module modules/mod_expires.so |

URL Rewriting with mod_rewrite

`apache

Enable rewrite engine

RewriteEngine On

Redirect www to non-www

RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC] RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

Force HTTPS

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

Pretty URLs

RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^([^/]+)/?$ /profile.php?username=$1 [L,QSA]

Remove file extensions

RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule (.*) $1.php [L] `

Log Management

Log Files

| Log Type | Default Location (Ubuntu) | Default Location (CentOS) | |----------|---------------------------|----------------------------| | Access Log | /var/log/apache2/access.log | /var/log/httpd/access_log | | Error Log | /var/log/apache2/error.log | /var/log/httpd/error_log |

Log Configuration

`apache

Error log configuration

ErrorLog "/var/log/apache2/error.log" LogLevel warn

Access log configuration

LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined LogFormat "%h %l %u %t \"%r\" %>s %O" common LogFormat "%{Referer}i -> %U" referer LogFormat "%{User-agent}i" agent

CustomLog "/var/log/apache2/access.log" combined `

Custom Log Formats

`apache

Define custom log format

LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %D" custom

Use custom format

CustomLog "/var/log/apache2/custom.log" custom

Conditional logging

SetEnvIf Remote_Addr "127\.0\.0\.1" dontlog CustomLog "/var/log/apache2/access.log" combined env=!dontlog `

Log Rotation

Create logrotate configuration:

`bash

Create logrotate configuration

sudo nano /etc/logrotate.d/apache2 `

` /var/log/apache2/*.log { daily missingok rotate 52 compress delaycompress notifempty create 640 root adm sharedscripts postrotate if /bin/systemctl status apache2 > /dev/null ; then \ /bin/systemctl reload apache2 > /dev/null; \ fi; endscript } `

SSL/TLS Configuration

Enabling SSL Module

`bash

Ubuntu/Debian

sudo a2enmod ssl sudo systemctl restart apache2

CentOS/RHEL

SSL module is usually enabled by default

`

SSL Virtual Host Configuration

`apache ServerName www.example.com DocumentRoot "/var/www/html" # SSL Engine SSLEngine on # SSL Certificates SSLCertificateFile "/path/to/certificate.crt" SSLCertificateKeyFile "/path/to/private.key" SSLCertificateChainFile "/path/to/chain.crt" # SSL Protocol and Cipher Configuration SSLProtocol all -SSLv2 -SSLv3 -TLSv1 -TLSv1.1 SSLCipherSuite ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256 SSLHonorCipherOrder on # HSTS Header Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains" # Logging ErrorLog "/var/log/apache2/ssl_error.log" CustomLog "/var/log/apache2/ssl_access.log" combined `

SSL Security Configuration

`apache

Modern SSL configuration

SSLEngine on SSLProtocol all -SSLv2 -SSLv3 -TLSv1 -TLSv1.1 SSLCipherSuite ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384 SSLHonorCipherOrder on SSLCompression off SSLSessionTickets off

OCSP Stapling

SSLUseStapling on SSLStaplingCache shmcb:/var/run/ocsp(128000) `

Let's Encrypt Integration

`bash

Install Certbot

sudo apt install certbot python3-certbot-apache

Obtain certificate

sudo certbot --apache -d example.com -d www.example.com

Test automatic renewal

sudo certbot renew --dry-run

Set up automatic renewal

echo "0 12 * /usr/bin/certbot renew --quiet" | sudo crontab - `

Troubleshooting

Common Issues and Solutions

| Issue | Possible Cause | Solution | |-------|----------------|----------| | 403 Forbidden | Incorrect permissions | Check file/directory permissions | | 404 Not Found | Wrong DocumentRoot | Verify DocumentRoot setting | | 500 Internal Server Error | Configuration error | Check error logs | | Apache won't start | Port already in use | Check for conflicting services | | SSL certificate errors | Wrong certificate path | Verify certificate file paths |

Diagnostic Commands

`bash

Check Apache configuration syntax

sudo apache2ctl configtest

or

sudo httpd -t

Check loaded modules

apache2ctl -M

or

httpd -M

Check virtual hosts

apache2ctl -S

or

httpd -S

Check Apache processes

ps aux | grep apache

or

ps aux | grep httpd

Check listening ports

sudo netstat -tlnp | grep :80 sudo netstat -tlnp | grep :443

Test specific configuration

apache2ctl -t -D DUMP_VHOSTS `

Log Analysis

`bash

Monitor error log in real-time

sudo tail -f /var/log/apache2/error.log

Search for specific errors

grep "Internal Server Error" /var/log/apache2/error.log

Analyze access patterns

awk '{print $1}' /var/log/apache2/access.log | sort | uniq -c | sort -nr | head -10

Check for 404 errors

grep " 404 " /var/log/apache2/access.log `

Commands Reference

Service Management

| Command | Description | |---------|-------------| | sudo systemctl start apache2 | Start Apache service | | sudo systemctl stop apache2 | Stop Apache service | | sudo systemctl restart apache2 | Restart Apache service | | sudo systemctl reload apache2 | Reload configuration | | sudo systemctl status apache2 | Check service status | | sudo systemctl enable apache2 | Enable auto-start | | sudo systemctl disable apache2 | Disable auto-start |

Configuration Management

`bash

Test configuration

sudo apache2ctl configtest

Graceful restart

sudo apache2ctl graceful

Show compiled-in modules

apache2ctl -l

Show loaded modules

apache2ctl -M

Show virtual host settings

apache2ctl -S

Show version information

apache2ctl -v `

Site Management (Debian/Ubuntu)

`bash

Enable site

sudo a2ensite sitename

Disable site

sudo a2dissite sitename

Enable module

sudo a2enmod modulename

Disable module

sudo a2dismod modulename

List available sites

ls /etc/apache2/sites-available/

List enabled sites

ls /etc/apache2/sites-enabled/ `

File and Directory Commands

`bash

Set proper ownership

sudo chown -R www-data:www-data /var/www/html/

Set proper permissions for directories

find /var/www/html/ -type d -exec chmod 755 {} \;

Set proper permissions for files

find /var/www/html/ -type f -exec chmod 644 {} \;

Create .htaccess file

touch /var/www/html/.htaccess

Create password file

sudo htpasswd -c /etc/apache2/.htpasswd username `

Performance Monitoring

`bash

Monitor server status (if mod_status enabled)

curl http://localhost/server-status

Monitor active connections

ss -tuln | grep :80

Check memory usage

free -h

Monitor Apache processes

top -p $(pgrep apache2 | tr '\n' ',' | sed 's/,$//') `

Backup and Maintenance

`bash

Backup configuration

sudo tar -czf apache-config-backup-$(date +%Y%m%d).tar.gz /etc/apache2/

Backup website files

sudo tar -czf website-backup-$(date +%Y%m%d).tar.gz /var/www/

Rotate logs manually

sudo logrotate -f /etc/logrotate.d/apache2

Clean old log files

find /var/log/apache2/ -name ".log." -mtime +30 -delete `

This comprehensive guide covers the essential aspects of Apache HTTP Server configuration, management, and optimization. Regular monitoring, proper security configuration, and performance tuning are crucial for maintaining a robust web server environment. Always test configuration changes in a development environment before applying them to production servers.

Tags

  • system-administration

Related Articles

Popular Technical Articles & Tutorials

Explore our comprehensive collection of technical articles, programming tutorials, and IT guides written by industry experts:

Browse all 8+ technical articles | Read our IT blog

Apache HTTP Server: Complete Guide and Documentation