Apache Server Configuration: The Ultimate Cheat Sheet

Introduction

Apache HTTP Server (Apache) is the world’s most widely used web server software, powering approximately 25% of all active websites on the internet. It’s an open-source, cross-platform software that handles HTTP requests and serves web content. Apache’s popularity stems from its reliability, flexibility, and extensive feature set through its modular architecture.

Core Concepts

ConceptDescription
Virtual HostsAllow a single Apache instance to serve multiple websites
DirectivesConfiguration commands that control Apache’s behavior
ModulesExtensions that add functionality to the core server
Configuration FilesText files containing directives that configure the server
Directory ContextSections in configuration files that apply settings to specific directories

Essential Configuration Files

File/DirectoryPurpose
/etc/apache2/ or /etc/httpd/Main configuration directory
apache2.conf or httpd.confMain configuration file
sites-available/Directory containing available virtual host configurations
sites-enabled/Directory containing enabled virtual host configurations (symlinks)
mods-available/Directory containing available module configurations
mods-enabled/Directory containing enabled module configurations (symlinks)
.htaccessDirectory-level configuration file for overriding server settings

Basic Apache Configuration Directives

Server Settings

# Server identification
ServerName example.com
ServerAdmin webmaster@example.com
ServerTokens Prod
ServerSignature Off

# Performance settings
Timeout 300
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5

Directory Access Control

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

<Directory /private>
    Options None
    AllowOverride None
    Require all denied
</Directory>

Virtual Host Configuration

<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/example.com
    ErrorLog ${APACHE_LOG_DIR}/example.com_error.log
    CustomLog ${APACHE_LOG_DIR}/example.com_access.log combined
</VirtualHost>

Understanding Apache Options

OptionDescription
IndexesAllows directory listing when no index file exists
FollowSymLinksAllows Apache to follow symbolic links
SymLinksIfOwnerMatchFollows symbolic links only if owner matches
ExecCGIAllows execution of CGI scripts
MultiViewsEnables content negotiation
AllEnables all options except MultiViews
NoneDisables all options

AllowOverride Settings

SettingDescription
AllAllow all .htaccess directives
NoneDisable .htaccess completely
AuthConfigAllow authentication directives
FileInfoAllow directives controlling document types
IndexesAllow directives controlling directory indexing
LimitAllow directives controlling host access
Options[=Option,...]Allow directives controlling specific options

Security Configurations

Restricting Access

# By IP
<Directory /protected>
    Require ip 192.168.1.0/24
</Directory>

# By hostname
<Directory /protected>
    Require host example.org
</Directory>

# Basic Authentication
<Directory /protected>
    AuthType Basic
    AuthName "Restricted Area"
    AuthUserFile /etc/apache2/.htpasswd
    Require valid-user
</Directory>

SSL Configuration

<VirtualHost *:443>
    ServerName example.com
    DocumentRoot /var/www/example.com
    
    SSLEngine on
    SSLCertificateFile /path/to/certificate.crt
    SSLCertificateKeyFile /path/to/private.key
    SSLCertificateChainFile /path/to/chain.crt
    
    # Strong SSL settings
    SSLProtocol all -SSLv2 -SSLv3 -TLSv1 -TLSv1.1
    SSLCipherSuite HIGH:!aNULL:!MD5:!3DES
    SSLHonorCipherOrder on
    Header always set Strict-Transport-Security "max-age=63072000; includeSubdomains; preload"
</VirtualHost>

Rewrite Rules and URL Manipulation

Enable Rewrite Module

sudo a2enmod rewrite
sudo systemctl restart apache2

Common Rewrite Rules

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

# www to non-www
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

# Clean URLs
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^([^/]+)/([^/]+)/?$ index.php?category=$1&item=$2 [NC,L]

Performance Optimization

Caching Directives

# Enable browser caching
<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType image/jpg "access plus 1 year"
    ExpiresByType image/jpeg "access plus 1 year"
    ExpiresByType image/gif "access plus 1 year"
    ExpiresByType image/png "access plus 1 year"
    ExpiresByType text/css "access plus 1 month"
    ExpiresByType application/javascript "access plus 1 month"
    ExpiresDefault "access plus 2 days"
</IfModule>

# Enable compression
<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript application/x-javascript application/json
</IfModule>

MPM Configuration

# Prefork MPM (stable, compatible)
<IfModule mpm_prefork_module>
    StartServers             5
    MinSpareServers          5
    MaxSpareServers         10
    MaxRequestWorkers      150
    MaxConnectionsPerChild   0
</IfModule>

# Worker MPM (threaded)
<IfModule mpm_worker_module>
    StartServers             2
    MinSpareThreads         25
    MaxSpareThreads         75
    ThreadLimit             64
    ThreadsPerChild         25
    MaxRequestWorkers      150
    MaxConnectionsPerChild   0
</IfModule>

# Event MPM (best performance for HTTP/1.1)
<IfModule mpm_event_module>
    StartServers             2
    MinSpareThreads         25
    MaxSpareThreads         75
    ThreadLimit             64
    ThreadsPerChild         25
    MaxRequestWorkers      150
    MaxConnectionsPerChild   0
</IfModule>

Common Challenges and Solutions

ChallengeSolution
403 Forbidden errorsCheck directory permissions; ensure Apache user can access files (usually www-data)
500 Internal Server errorsCheck Apache error logs; verify syntax in configuration files and .htaccess
Slow performanceEnable caching, compression; optimize MPM settings; monitor resource usage
Cannot override settings with .htaccessEnsure AllowOverride is set to All or appropriate value
SSL certificate issuesVerify certificate paths and permissions; check certificate chain order
Rewrite rules not workingEnsure mod_rewrite is enabled; check RewriteBase directive; use [L] flag

Command-Line Tools

Apache Control Commands

# Ubuntu/Debian
sudo systemctl start apache2
sudo systemctl stop apache2
sudo systemctl restart apache2
sudo systemctl reload apache2
sudo systemctl status apache2

# CentOS/RHEL
sudo systemctl start httpd
sudo systemctl stop httpd
sudo systemctl restart httpd
sudo systemctl reload httpd
sudo systemctl status httpd

Managing Modules

# Ubuntu/Debian
sudo a2enmod module_name    # Enable a module
sudo a2dismod module_name   # Disable a module

# CentOS/RHEL
sudo yum install mod_modulename   # Install a module

Managing Virtual Hosts

# Ubuntu/Debian
sudo a2ensite site_name.conf    # Enable a site
sudo a2dissite site_name.conf   # Disable a site

Testing Configuration

# Check configuration syntax
sudo apachectl configtest
# or
sudo apache2ctl -t

# Show compiled modules
apache2ctl -M

Best Practices

  1. Security

    • Hide server information using ServerTokens Prod and ServerSignature Off
    • Implement strong SSL/TLS settings and enforce HTTPS
    • Restrict directory access using appropriate Require directives
    • Regularly update Apache and all modules
  2. Performance

    • Enable caching for static assets
    • Configure compression for text-based content
    • Choose appropriate MPM based on workload
    • Monitor and tune MaxRequestWorkers based on available memory
  3. Maintenance

    • Use separate configuration files for virtual hosts
    • Store site-specific configurations in virtual host files, not .htaccess
    • Document configuration changes
    • Implement proper logging and monitoring
    • Back up configuration files before making changes
  4. Organization

    • Use the Include directive to organize configuration into logical files
    • Maintain a consistent naming convention for virtual hosts
    • Comment configurations adequately

Resources for Further Learning

Scroll to Top