IT Course Directory: VMware, Linux, Networking, and Raspberry Pi
Apache Web Server Online Course
Learn to install, configure, secure, troubleshoot, and maintain Apache HTTP Server for static websites, virtual hosts, HTTPS, and web applications.
Apache HTTP Server is open-source software that receives web requests and serves files or forwards requests to application services. This course covers the complete workflow: install Apache, publish a static site, configure virtual hosts, enable HTTPS, protect private areas, reverse-proxy applications, monitor the server, and maintain changes safely.
1. Introduction to Apache HTTP Server
Apache is a web server. A browser or another client connects to Apache using HTTP or HTTPS. Apache examines the request, applies its configuration and enabled modules, then returns a response. The response might be an HTML file, an image, a redirect, an error, or data received from a backend application.
Common Apache uses include serving static websites, hosting several domains on one server with virtual hosts, terminating TLS connections, redirecting or rewriting URLs, authenticating users, and acting as a reverse proxy for applications.
Apache can process requests using different MPMs, or Multi-Processing Modules. An MPM determines whether Apache uses separate processes, worker processes with multiple threads, or an event-oriented model. Process-based operation can isolate requests more strongly, while threaded and event-based models can use resources efficiently. The best choice depends on workload, modules, operating-system package defaults, and application compatibility.
2. Web Server and HTTP Fundamentals
A typical request follows this sequence:
- The user enters a URL such as
https://www.example.com/guide/index.html. - DNS translates the domain name to an IP address.
- The client connects to a port, normally 80 for HTTP or 443 for HTTPS.
- Apache receives the request and selects a virtual host using the destination address, port, and Host header.
- Apache serves a file, applies a module, redirects the request, or forwards it to a backend.
- The client receives a status code, headers, and usually a response body.
A URL identifies a resource. A domain is a human-readable name; an IP address identifies a network interface; DNS maps names to addresses; a port identifies a service endpoint; and a protocol defines communication rules.
HTTP methods describe actions. GET retrieves data, POST submits data, PUT replaces data, PATCH partially updates data, and DELETE requests deletion. Headers carry metadata such as the requested host, content type, cache instructions, cookies, and authentication information. MIME types, such as text/html, text/css, image/png, and application/json, tell the client how to interpret content.
The DocumentRoot is the filesystem directory from which Apache serves a website. A request for /images/logo.png may map to /var/www/example.com/public/images/logo.png. HTTP sends data without transport encryption. HTTPS is HTTP protected by TLS, which provides encryption, server identity verification, and integrity protection.
3. Installing and Managing Apache
Package and service names differ by Linux family. Debian-based distributions commonly use the apache2 package and service. Red Hat-based distributions commonly use the httpd package and service.
| Platform family | Package name | Service name | Main configuration path | Virtual host configuration location | Log location |
|---|---|---|---|---|---|
| Debian-based | apache2 | apache2 | /etc/apache2/apache2.conf | /etc/apache2/sites-available and sites-enabled | /var/log/apache2 |
| Red Hat-based | httpd | httpd | /etc/httpd/conf/httpd.conf | /etc/httpd/conf.d | /var/log/httpd |
# Debian-based systems
sudo apt update && sudo apt install apache2
sudo systemctl enable --now apache2
# Red Hat-based systems
sudo dnf install httpd
sudo systemctl enable --now httpdService operations are usually performed with systemctl.
| Task | systemd command | Purpose | When to use it |
|---|---|---|---|
| Start | sudo systemctl start apache2 | Start the service now | After installation or a stop |
| Stop | sudo systemctl stop apache2 | Stop request processing | Maintenance or emergency isolation |
| Restart | sudo systemctl restart apache2 | Stop and start the service | Changes requiring a full restart |
| Reload | sudo systemctl reload apache2 | Apply configuration without a full stop | Normal configuration changes |
| Enable | sudo systemctl enable apache2 | Start at boot | Persistent server operation |
| Check | sudo systemctl status apache2 | Show state and recent diagnostics | After changes or failures |
Use httpd instead of apache2 on many Red Hat-based systems. Confirm installation with a browser pointed at the server IP or with:
curl -I http://127.0.0.1A working default installation normally returns an HTTP response such as 200 OK.
4. Filesystem Layout and Core Configuration
Apache configuration is divided into a main file and included fragments. Debian-based systems commonly separate enabled sites and modules using symbolic links in sites-enabled and mods-enabled. Red Hat-based systems commonly load additional configuration files from conf.d and module definitions from package-managed locations.
Important locations include the main configuration file, virtual-host definitions, module files, document roots, access logs, and error logs. Do not assume that a path from one distribution exists on another.
Apache directives use a name followed by arguments. A directive can appear globally, inside a VirtualHost block, or inside a Directory block. Context determines where it is valid. More specific settings generally override broader settings, subject to directive rules and included-file order. Lines beginning with # are comments.
| Directive | Purpose | Valid configuration context | Example use |
|---|---|---|---|
DocumentRoot | Select site files | Server, virtual host | DocumentRoot /var/www/site/public |
ServerName | Set the primary hostname | Server, virtual host | ServerName example.com |
ServerAlias | Add hostnames | Virtual host | ServerAlias www.example.com |
DirectoryIndex | Choose default index files | Directory, virtual host, server | DirectoryIndex index.html |
Require | Authorize access | Directory, location, virtual host | Require all granted |
AllowOverride | Control permitted .htaccess settings | Directory | AllowOverride None |
Redirect | Send a redirect response | Server, virtual host, directory | Redirect permanent / https://example.com/ |
A .htaccess file is a per-directory configuration file. Apache reads it only when the parent directory permits the required settings with AllowOverride. Prefer central configuration when possible because it is easier to validate and can be more efficient.
Always validate before applying a change:
sudo apachectl configtest
# On some systems:
sudo httpd -t
sudo systemctl reload apache25. Hosting Static Content
Create a separate document root for each site. Put HTML, CSS, JavaScript, images, downloads, and other public files below that directory. A simple page can be created with:
sudo mkdir -p /var/www/example.com/public
sudo sh -c 'printf "<h1>Example site</h1>\n" > /var/www/example.com/public/index.html'
sudo chown -R www-data:www-data /var/www/example.comThe web-server account varies by distribution. Use the account supplied by the package and grant only the access needed. Files need read permission, and every parent directory needs execute permission for traversal. Avoid making the entire tree world-writable.
DirectoryIndex controls default files such as index.html. Disable directory listings unless they are intentionally required. A common directory policy is:
<Directory /var/www/example.com/public>
Require all granted
Options -Indexes +FollowSymLinks
DirectoryIndex index.html
AllowOverride None
</Directory>6. Virtual Hosts
A virtual host is an independent Apache site definition, usually identified by a hostname and port. Name-based virtual hosting lets one IP address serve multiple domains. IP-based virtual hosting assigns different IP addresses to different virtual hosts and is less commonly needed for ordinary websites.
<VirtualHost *:80>
ServerName example.com
ServerAlias www.example.com
ServerAdmin admin@example.com
DocumentRoot /var/www/example.com/public
<Directory /var/www/example.com/public>
Require all granted
Options -Indexes +FollowSymLinks
AllowOverride None
</Directory>
ErrorLog ${APACHE_LOG_DIR}/example.com-error.log
CustomLog ${APACHE_LOG_DIR}/example.com-access.log combined
</VirtualHost>DNS records for the domain must point to the server. Before DNS is available, controlled testing can map a name to an IP address in the client’s hosts file. Test the Host header directly when necessary:
curl -I -H 'Host: example.com' http://SERVER_IP/Apache selects among matching virtual hosts using address, port, and hostname. If no hostname matches, the first or default virtual host for that address and port may receive the request. On Debian-based systems, enable a site with a2ensite; disable it with a2dissite; then validate and reload.
7. Modules
A module is an optional Apache component that adds functionality. Modules must be loaded, enabled, and compatible with the active MPM and other modules. Enable only what the server needs.
| Module | Capability | Typical use case | Security or operational note |
|---|---|---|---|
mod_rewrite | Pattern-based URL rewriting | Canonical URLs and application routing | Review rules to prevent loops and unintended exposure |
mod_ssl | TLS support | HTTPS virtual hosts | Protect private keys and use current TLS settings |
mod_headers | Request and response headers | Security and proxy headers | Do not trust client-supplied forwarding headers blindly |
mod_deflate | Compression | Compress text responses | Avoid wasteful compression of already-compressed files |
mod_proxy and mod_proxy_http | Reverse proxying | Forward traffic to applications | Do not create an unintended open proxy |
mod_auth_basic | Basic authentication | Protect administrative paths | Use HTTPS because credentials are otherwise exposed |
mod_status | Runtime status | Operational diagnosis | Restrict access to administrators |
| PHP integration | Execute PHP | PHP sites using a module or PHP-FPM | Keep the runtime and packages patched |
sudo a2enmod ssl rewrite headers proxy proxy_http
sudo systemctl reload apache28. Rewriting and Redirects
A redirect tells the client to request another URL. A temporary redirect commonly uses status 302 or 307; a permanent redirect commonly uses 301 or 308. Use redirects when the public URL should change, such as moving HTTP to HTTPS or consolidating a canonical hostname.
A rewrite changes request handling inside Apache or maps a public path to another resource. RewriteRule supplies a pattern and replacement. RewriteCond adds a condition based on variables such as the hostname, protocol, or file state.
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]Preserve paths and query strings deliberately. Avoid loops by ensuring that a rule’s condition becomes false after the redirect. Test both the canonical and non-canonical forms with curl -I.
9. HTTPS and TLS
A TLS certificate is a digital credential that binds a hostname to a public key. The private key must remain secret. A certificate chain may include the site certificate and intermediate certificates leading to a trusted certificate authority. Browsers warn when the name, validity period, chain, or key relationship is incorrect.
<VirtualHost *:80>
ServerName example.com
Redirect permanent / https://example.com/
</VirtualHost>
<VirtualHost *:443>
ServerName example.com
DocumentRoot /var/www/example.com/public
SSLEngine on
SSLCertificateFile /etc/ssl/certs/example.com/fullchain.pem
SSLCertificateKeyFile /etc/ssl/private/example.com/privkey.pem
<Directory /var/www/example.com/public>
Require all granted
</Directory>
</VirtualHost>Obtain publicly trusted certificates through a recognized certificate authority and automate renewal where possible. Configure current TLS protocols and provider-recommended cipher settings rather than copying obsolete examples. Verify the certificate’s names, expiration, chain, and selected HTTPS virtual host with browser tools and a TLS client. A warning can result from an expired certificate, hostname mismatch, incomplete chain, unreadable key, or an old protocol configuration.
10. Access Control and Authentication
Authentication answers “Who are you?” Authorization answers “What are you allowed to access?” Apache authorization can allow or deny by IP address, host, user, or group. The modern authorization syntax commonly uses Require.
<Directory /var/www/example.com/private>
AuthType Basic
AuthName "Restricted Area"
AuthUserFile /etc/apache2/.htpasswd-example
Require valid-user
</Directory>Create password files with a suitable Apache utility, store them outside the public document root, restrict their ownership and permissions, and use Basic authentication only over HTTPS. Protect administrative paths with narrow authorization rules and, where appropriate, network restrictions or additional authentication factors.
11. Application Hosting and Reverse Proxying
Dynamic applications generate responses at request time. Apache can integrate PHP through a package module or forward PHP requests to PHP-FPM. Other applications can listen on a private local port while Apache remains the public-facing server.
<VirtualHost *:80>
ServerName app.example.com
ProxyPreserveHost On
ProxyPass / http://127.0.0.1:3000/
ProxyPassReverse / http://127.0.0.1:3000/
RequestHeader set X-Forwarded-Proto "http"
</VirtualHost>ProxyPass forwards requests and ProxyPassReverse adjusts redirect headers from the backend. Forwarded host, protocol, and client-address information must be configured and trusted carefully. Applications using WebSockets need the appropriate proxy support and upgrade handling. Keep backend ports bound to localhost or a protected network unless public access is required.
12. Performance and Resource Management
Choose an MPM according to workload and application requirements. Important settings include worker or thread counts, connection limits, keep-alive behavior, and request timeouts. Long timeouts and excessive concurrency can consume memory and file descriptors; values that are too low can reduce throughput.
Compress suitable text responses, send cache headers for versioned static assets, and optimize asset size. Measure before tuning. Monitor CPU, memory, disk I/O, network throughput, open connections, response latency, error rates, and backend latency. Use controlled load tests against systems you own or are authorized to test, and watch resource limits while testing.
13. Logging, Monitoring, and Troubleshooting
The Access Log records incoming requests and response details. Common fields include client address, timestamp, request line, status code, response size, referrer, and user agent. The Error Log records startup messages, warnings, configuration errors, permission failures, proxy failures, and application diagnostics.
| Status code | Meaning | Likely cause | First troubleshooting action |
|---|---|---|---|
| 200 | Success | Resource served normally | Check content and response headers |
| 301/302 | Redirect | Canonical URL, HTTPS, or rewrite rule | Inspect the Location header and follow the rule chain |
| 403 | Forbidden | Authorization or filesystem permission denial | Read the error log and inspect Directory rules and parent permissions |
| 404 | Not found | Wrong root, missing file, or rewrite error | Confirm the selected virtual host and requested path |
| 500 | Server error | Application or configuration failure | Inspect the error log and validate configuration |
| 502 | Bad gateway | Proxy could not obtain a valid backend response | Test the upstream service locally |
| 503 | Service unavailable | Stopped backend, overload, or maintenance state | Check service status, capacity, and proxy logs |
sudo apachectl configtest
sudo systemctl status apache2
sudo tail -n 50 /var/log/apache2/error.log
curl -I http://example.comFor a 403, check Require rules, file ownership, file modes, parent-directory traversal permissions, and operating-system security policies. For a 404, check DocumentRoot, the file path, host selection, and rewrite rules. If the default page appears, verify DNS, the Host header, enabled site files, and virtual-host ordering. For a 502 or 503, check that the backend is running, reachable at the configured address and port, and supported by the required proxy modules.
Monitor uptime, traffic, status-code rates, resource use, log volume, and certificate expiry. Log rotation is essential so busy servers do not fill their disks.
14. Security Hardening
- Keep the operating system, Apache, modules, TLS libraries, and application runtimes updated.
- Restrict filesystem access with narrow
Directoryrules and least-privilege ownership. - Disable directory indexes where listings are not required.
- Prevent access to credentials, private keys, source-control metadata, backups, and configuration files.
- Expose only required ports, normally 80 and 443, through the host and network firewalls.
- Set reasonable request-size, timeout, and connection limits to reduce resource abuse.
- Restrict status pages and administrative interfaces to authorized networks or users.
- Review access and error logs for scanning, repeated failures, unusual methods, and unexpected status-code spikes.
- Use HTTPS for credentials and sensitive content, and protect private keys with restrictive permissions.
15. Safe Operations and Maintenance
- Make a backup or create a version-controlled configuration change.
- Edit the smallest relevant file and document the purpose.
- Run
apachectl configtestorhttpd -t. - Reload Apache for normal configuration changes; use restart only when required.
- Verify the service status, expected URL, status code, logs, and application behavior.
- Roll back the change if validation or monitoring shows a regression.
Back up virtual-host files, module settings, TLS configuration references, site content, and application dependency information. Do not place private keys or password files in an unnecessarily broad-access repository. Maintain a record of domains, document roots, backends, ports, certificates, owners, renewal procedures, and rollback steps. Schedule log rotation, disk-space checks, certificate renewal checks, package updates, and periodic access-control reviews.
Practical Deployment Exercises
Publish a static website
Create a document root, add index.html, set suitable ownership and permissions, define a virtual host, validate the configuration, reload Apache, and confirm an HTTP 200 response.
Host two websites
Create separate roots and virtual-host blocks with distinct ServerName and ServerAlias values. Point DNS records to the server or use controlled hosts-file mappings. Test each hostname and confirm that it serves the intended content.
Move a site to HTTPS
Install a trusted certificate and private key, configure the port 443 virtual host, validate the chain and hostname, redirect HTTP to HTTPS, and test both the redirect and final certificate.
Protect a private area
Create a password file outside the document root, configure Basic authentication for a private directory, require valid users or approved groups, and confirm that unauthenticated requests receive a challenge.
Expose an application
Run the application on a local port, configure ProxyPass and ProxyPassReverse, pass required protocol and host information, and diagnose failures by testing the backend directly and reading the error log.
Exam-Relevant Notes
- DocumentRoot maps URL paths to files; ServerName identifies the primary hostname of a virtual host; ServerAlias adds alternate hostnames.
- Authentication identifies a user; authorization decides whether access is permitted.
- HTTPS is HTTP over TLS. Certificates prove identity; private keys must remain secret.
- A reload applies configuration with less disruption than a restart, but validation must happen first.
- A 403 usually indicates an access or permission problem; a 404 indicates a missing or incorrectly mapped resource; a 502 or 503 commonly indicates a backend problem.
- Least privilege means granting only the filesystem, network, and administrative access required.
- MPMs control Apache’s process and thread model and affect capacity and module compatibility.
Continue with the Apache course curriculum, review Linux fundamentals, or browse the wider course catalog.