Apache logoApache INTERMEDIATE

Apache

Apache cheat sheet for virtual hosts, .htaccess rules, mod_rewrite, SSL setup, modules, and performance tuning with config examples.

10 min read
apachehttpdweb-serverhtaccessvirtual-hostsmodulesrewritessl

Installation & Basic Commands

Installing and managing Apache

Installation

Installing Apache on different platforms

bash
🌐 Most widely used web server
📦 Available as apache2 or httpd package
🔧 Highly modular and extensible
⚡ Config at /etc/apache2/ or /etc/httpd/

Commands & Configuration

Service commands, config testing, and configuration file locations

bash
💡 Always run apachectl configtest before restarting — catches syntax errors without downtime
⚡ Use reload instead of restart for zero-downtime config changes in production
📌 Debian uses a2ensite/a2dissite; RHEL puts everything in /etc/httpd/conf.d/
🟢 apachectl -S shows which virtual hosts are active and what ports they listen on

Virtual Hosts

Configuring virtual hosts for multiple sites

Basic Virtual Host

Setting up a basic virtual host

apache
🌐 Virtual hosts allow multiple sites on one server
📝 Each vhost needs unique ServerName
🔗 Enable with a2ensite command
⚡ Name-based is most common type

SSL/TLS Configuration

Configuring HTTPS with SSL certificates

apache
🔒 Always use HTTPS in production
📜 Let's Encrypt for free SSL certificates
⚡ Enable HTTP/2 for better performance
🔐 HSTS header enforces HTTPS

Reverse Proxy

Proxy requests to backend application servers with mod_proxy

Reverse Proxy & Load Balancing

Forward requests to Node.js, Python, or other backend servers

apacheconf
💡 ProxyPreserveHost On sends the original Host header to the backend — essential for virtual hosts
⚡ Use ProxyPass /path ! to exclude paths from proxying (serve static files directly)
📌 WebSocket proxying needs mod_proxy_wstunnel and RewriteRule for the Upgrade header
🟢 Load balancing with BalancerMember distributes traffic across multiple backend instances
proxyreverse-proxyload-balancing

.htaccess & URL Rewriting

Directory-level configuration and URL rewriting

.htaccess Basics

Common .htaccess configurations

apache
📁 .htaccess provides directory-level config
🔒 Requires AllowOverride All in vhost
⚡ Can impact performance if overused
🎯 Great for shared hosting environments

URL Rewriting

Advanced URL rewriting with mod_rewrite

apache
🔄 mod_rewrite is powerful but complex
📝 Test rules carefully with RewriteLog
🎯 Order matters - most specific first
⚡ Use RewriteCond for conditional rules

Redirects & Error Pages

Simple redirects with mod_alias and custom error pages

apacheconf
💡 Use Redirect (mod_alias) for simple URL redirects — mod_rewrite is overkill for basic cases
⚡ 301 is permanent (cached by browsers, transfers SEO); 302 is temporary (not cached)
📌 Force HTTPS with RewriteCond %{HTTPS} off — the most common rewrite rule on the web
🟢 ErrorDocument paths are relative to DocumentRoot — create an /errors/ directory for custom pages
redirecterror-pageshttps

Logging

Configure access logs, error logs, and custom log formats

Access & Error Logs

Configure log files, formats, and rotation

apacheconf
💡 Use combined format for access logs — it includes Referer and User-Agent for analysis
⚡ Set LogLevel rewrite:trace3 to debug mod_rewrite rules — essential when rules don't work
📌 Use SetEnvIf to exclude health checks and bots from access logs — keeps logs clean
🟢 Pipe logs to rotatelogs for automatic rotation without logrotate config
loggingaccess-logerror-log

Security & Access Control

Securing your Apache server

Authentication & Access Control

Password-protect directories and restrict access by IP

apacheconf
💡 htpasswd -c creates the file — omit -c when adding users to an existing file or it overwrites
⚡ Options -Indexes prevents directory listing — always disable this in production
📌 Block .env, .git, and backup files with FilesMatch — they should never be web-accessible
🟢 Combine Require valid-user + Require ip inside <RequireAll> for defense in depth
authhtpasswdaccess-control

Security Best Practices

Essential security configurations

apache
🔒 Hide version info and disable directory listing
🛡️ Use security headers to prevent attacks
⚠️ Implement ModSecurity for WAF protection
🔐 Use fail2ban to block attackers

Headers & CORS

Set security headers and configure CORS with mod_headers

apacheconf
💡 ServerTokens Prod hides your Apache version from response headers — basic security hygiene
⚡ HSTS with preload tells browsers to ALWAYS use HTTPS — submit to hstspreload.org
📌 Never use Access-Control-Allow-Origin "*" with credentials — use specific origins instead
🟢 Use SetEnvIf to dynamically set CORS origin from a whitelist of allowed domains
headerscorssecurity

Modules & Performance

Apache modules and performance optimization

Essential Modules

Common Apache modules and their usage

bash
🔧 Apache has 100+ available modules
📦 Enable only needed modules for performance
⚡ mod_deflate saves bandwidth
🔒 mod_security adds WAF capabilities

Caching & Compression

Enable GZIP compression and browser caching for performance

apacheconf
💡 GZIP compression reduces text-based response sizes by 60-80% — enable it on every server
⚡ Set "access plus 1 year" for static assets with fingerprinted filenames (style.a1b2c3.css)
📌 HTML should have Cache-Control: no-cache so users always get the latest content
🟢 Use immutable with long max-age for hashed/fingerprinted assets — browsers skip revalidation
cachingcompressiongzipperformance

Performance Tuning

Optimizing Apache for better performance

apache
⚙️ Choose appropriate MPM for workload
🗜️ Enable compression for text content
💾 Use caching for static content
📊 Monitor with mod_status