VMware ESXi and vSphere Cluster Management

Apache Web Server Administration

Learn to configure, secure, monitor, and troubleshoot Apache HTTP Server with virtual hosts, TLS, proxies, logs, and mod_status.

Apache HTTP Server is a web server that accepts HTTP and HTTPS requests and returns static files, generated application responses, or proxy responses from backend services. It can host several websites on one machine, terminate TLS, record request activity, and expose operational statistics.

This lesson assumes familiarity with the Linux command line, file permissions, IP addresses, ports, DNS, HTTP requests, text configuration files, and system services.

Apache administration fundamentals

Apache is commonly placed at the edge of a web application. For a static site, it reads files from a document root. For an application, it may pass requests to PHP-FPM, a local application server, or another HTTP service. Modules add capabilities such as TLS, proxying, URL rewriting, authentication, and runtime status reporting.

Configuration layout

The main configuration file is usually named httpd.conf or apache2.conf. It normally includes smaller files for modules, ports, security defaults, and virtual hosts. Separating site-specific settings from global settings makes changes easier to review and reduces the chance that one site affects another.

Platform familyPrimary configuration locationVirtual-host configuration locationLog locationService name
Debian-style Linux/etc/apache2/apache2.conf/etc/apache2/sites-available/ and /etc/apache2/sites-enabled//var/log/apache2/apache2
RHEL-style Linux/etc/httpd/conf/httpd.conf/etc/httpd/conf.d//var/log/httpd/httpd

Distribution layouts vary, so confirm included files and active paths on the target host. Apache configuration commonly contains global directives, module configuration, site or VirtualHost blocks, and logging directives.

ModuleFeature enabledTypical use
mod_sslHTTPS and TLSCertificates and encrypted connections
mod_proxyProxy frameworkForward and reverse proxying
mod_proxy_httpHTTP proxy supportProxying to HTTP backends
mod_statusRuntime statisticsWorker and request monitoring
mod_rewriteURL and request rewritingRedirects and application routing

Service lifecycle and safe changes

Check the configuration before every reload or restart. A graceful reload applies updated settings while allowing existing requests to finish. A restart is more disruptive and may be needed when a module or process-level setting changes.

apachectl configtest
apachectl -t
systemctl status apache2
systemctl reload apache2
systemctl restart httpd

Use the service name and commands appropriate for the distribution. A successful syntax test does not prove that a backend is reachable, a certificate is valid, or a filesystem path has the intended permissions.

Virtual hosts

A VirtualHost is a configuration block for one website or endpoint. Name-based virtual hosting allows multiple hostnames to share one IP address. Apache examines the connection address and the HTTP Host header, then selects the matching virtual host. IP-based hosting assigns different IP addresses to different virtual hosts and is less commonly required today.

Basic name-based configuration

<VirtualHost *:80>
    ServerName example.test
    ServerAlias www.example.test
    DocumentRoot /var/www/example
    ErrorLog ${APACHE_LOG_DIR}/example-error.log
    CustomLog ${APACHE_LOG_DIR}/example-access.log combined

    <Directory /var/www/example>
        Require all granted
    </Directory>
</VirtualHost>
DirectivePurposeExample valueCommon error
ServerNamePrimary hostname matched by the siteexample.testHostname does not match the request
ServerAliasAdditional matching hostnamewww.example.testAlias omitted or misspelled
DocumentRootDirectory containing served content/var/www/exampleWrong directory or missing files
<Directory>Filesystem authorization and behaviorRequire all grantedAccess denied because authorization is absent
ErrorLogSite-specific error log/var/log/apache2/example-error.logCannot locate the relevant diagnostic message
CustomLogSite-specific access log and formatcombinedRequests are mixed with other sites

On Debian-style systems, place the file under sites-available and enable it with a2ensite example.conf. On other distributions, place or include the fragment according to the local layout. Always validate and reload afterward.

a2ensite example.conf
apachectl -t
systemctl reload apache2

If no virtual host matches the requested hostname, Apache uses the default virtual host for that address and port. The first loaded virtual host often becomes the default. This explains why an unexpected website can appear when DNS, ServerName, or ServerAlias is wrong.

Files, ownership, and routing tests

Give each site its own document root and log files. Web content should be readable by the Apache service account, while writable directories should be limited to the application components that require them. Do not make the entire document root world-writable. Configuration, private keys, and logs need stricter permissions than public files.

DNS must resolve each hostname to the correct server. During testing, a hosts-file entry can map a name to an address without changing public DNS. You can also test routing directly with a Host header.

curl -I http://example.test/
curl -H 'Host: example.test' http://127.0.0.1/

Access and error logs

An access.log records requests and responses. An error.log records startup messages, configuration failures, permission errors, proxy failures, TLS problems, and other processing diagnostics. The two logs answer different questions: the access log shows what clients requested and received; the error log helps explain why.

A combined access entry commonly contains the client address, timestamp, HTTP method, requested URL, protocol, response status, response size, referrer, and user agent. Formats can be customized with LogFormat and selected with CustomLog.

Field or status codeMeaningAdministrative interpretation
Client addressObserved source addressUseful for traffic analysis, but may be a proxy or NAT address
Request lineMethod, path, and protocolShows the exact resource and method requested
200Successful responseContent was returned successfully
301/302RedirectCheck redirect targets and possible loops
403ForbiddenInspect authorization rules and filesystem traversal permissions
404Not foundCheck the path, document root, rewrite rules, and deployment
500Application or server errorInspect the error log and backend application logs
502/503Bad or unavailable gateway serviceCheck reverse-proxy connectivity and backend health

LogLevel controls the minimum severity recorded in the error log. Lower-severity diagnostic messages provide more detail but can increase volume. Raise detail temporarily while investigating, then restore an appropriate production level.

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

Logs may exist globally or inside individual virtual hosts. Configure rotation so old files are compressed, retained for a defined period, and removed according to policy. Without rotation, high traffic can exhaust disk space and cause outages.

Logs can contain IP addresses, URLs with query strings, referrers, user agents, usernames, tokens, or other personal information. Restrict access, avoid logging secrets, define retention periods, and protect transferred or centralized logs.

SSL/TLS and HTTPS

HTTPS is HTTP carried inside a TLS-protected connection. TLS encrypts traffic and lets a client verify the server identity. mod_ssl supplies Apache's TLS support. A certificate is a signed public-key document identifying hostnames; its paired private key must remain confidential.

Enable the TLS module and ensure Apache listens on port 443. Certificates may be issued by a public certificate authority, an internal authority, or created for testing. Production certificates should have correct names, valid dates, and a usable trust chain.

a2enmod ssl
<VirtualHost *:443>
    ServerName example.test
    DocumentRoot /var/www/example
    SSLEngine on
    SSLCertificateFile /etc/ssl/certs/example.test.crt
    SSLCertificateKeyFile /etc/ssl/private/example.test.key
    # Configure a chain file when the certificate deployment requires one.
    # SSLCertificateChainFile /etc/ssl/certs/example-chain.crt
</VirtualHost>

Certificate name matching is essential: a certificate for one hostname may not be valid for another. Also check expiration, the complete intermediate chain, and that the configured certificate matches the private key. Protect private-key files with ownership and permissions that allow Apache to read them at startup but prevent ordinary users from reading them.

Where appropriate, redirect HTTP to HTTPS with a deliberate redirect rule. Confirm that applications, cookies, absolute URLs, and health checks work over the new scheme. Use modern protocol and cipher settings supplied by the supported Apache and operating-system versions rather than copying obsolete compatibility settings.

openssl s_client -connect example.test:443 -servername example.test
curl -I https://example.test/

Renew certificates before expiry and reload Apache after replacing them. A reload normally avoids interrupting established connections, but verify the newly presented certificate from a client.

Forward proxy configuration

A forward proxy is a client-facing intermediary. The client asks Apache to fetch an outbound resource, so the destination sees the proxy as the requester. A reverse proxy has the opposite relationship: clients address Apache as the service, and Apache forwards selected requests to internal backends.

CharacteristicForward proxyReverse proxy
Primary usersClients or client networksPublic clients of an application
DestinationUsually arbitrary permitted external hostsConfigured internal backend services
VisibilityDestination may see the proxy addressClient sees Apache, not necessarily the backend
Main riskBecoming an open proxy used for abuseExposing or misrouting internal services

Forward proxying requires the proxy framework and the protocol-specific modules needed for requested destinations. Permit only known client networks, and consider authentication. Restrict ordinary proxy requests and HTTPS CONNECT tunnels independently where supported. Never expose an unrestricted forward proxy to the internet.

a2enmod proxy proxy_http

Monitor proxy logs for unusual destinations, volume, authentication failures, and tunnel abuse. If the function is not required, disable the proxy modules or remove the forward-proxy configuration. A command-line test can use a local proxy explicitly, for example:

curl -x http://proxy.example.test:3128 https://www.example.test/

Reverse proxying

A reverse proxy places Apache in front of an application server. The request flow is client to Apache, Apache to the backend, and the response back through Apache to the client. This can provide a stable public hostname, TLS termination, access logging, and a controlled boundary around a backend.

a2enmod proxy proxy_http
ProxyPass /app/ http://127.0.0.1:8080/
ProxyPassReverse /app/ http://127.0.0.1:8080/

ProxyPass maps a public path to a backend URL. ProxyPassReverse adjusts selected backend response headers, such as redirects, so they refer to the public Apache URL rather than an internal address. Pay close attention to trailing slashes and path prefixes.

Choose the backend protocol and load its module, such as HTTP or another supported protocol. Applications often need accurate information about the original host, scheme, and client address. Configure appropriate request headers and ensure the backend trusts them only from Apache; otherwise clients may spoof identity-related headers.

Review backend redirects, cookies, URL prefixes, request-body limits, connection and response timeouts, and error handling. A reverse proxy is not the same as a redirect: a redirect tells the client to make a new request, while proxying keeps the backend request behind Apache. Direct content serving reads files locally and does not involve a backend process.

Test the backend from the Apache host, check that its process is listening on the expected address and port, and avoid exposing a backend publicly unless required. Use health checks, resource limits, and logs to distinguish an unavailable application from an Apache configuration error.

Server statistics with mod_status

mod_status exposes current Apache runtime information. The usual endpoint is /server-status. It can show uptime, request rate, total traffic, active requests, busy and idle workers, worker states, and a scoreboard. The scoreboard represents how workers are being used; exact symbols and fields depend on the Apache processing model and version.

a2enmod status
<Location /server-status>
    SetHandler server-status
    Require ip 127.0.0.1 ::1 192.0.2.0/24
</Location>

Restrict this endpoint to localhost, a trusted administrator network, or a monitoring system. Do not publish it openly: status output can reveal request paths, client information, worker pressure, and backend behavior. Some installations support machine-readable output and refresh parameters; enable or consume those features only within the access restrictions.

IndicatorWhat it representsPotential concern
UptimeTime since the server or worker set startedUnexpected resets or frequent restarts
Requests per secondCurrent or average request rateTraffic spike or capacity pressure
Busy workersWorkers handling requestsValues near the configured limit can cause queuing
Idle workersWorkers available for new requestsNone available may indicate saturation
ScoreboardIndividual worker statesMany long-running or stuck workers need investigation
Bytes and traffic totalsVolume served by ApacheUnexpected growth or bandwidth pressure

Use status data with access and error logs. A traffic spike, exhausted workers, or many long-running requests may point to slow clients, expensive application calls, backend timeouts, or insufficient capacity. The status page is a signal, not a complete performance-monitoring system.

Troubleshooting Apache

Reload failures

If Apache will not reload, run apachectl configtest or apachectl -t. Read the reported file and line, then check for invalid syntax, disabled modules, missing certificate or log files, duplicate virtual hosts, and malformed directives. Correct the error before attempting another reload.

Wrong website for a hostname

Verify DNS, the enabled site, and the ServerName and ServerAlias values. Inspect the loaded virtual-host map if the distribution provides a tool for it. Test the local listener with a deliberate Host header. If the hostname does not match, the default virtual host may answer.

HTTP 404 or 403 responses

Use the access log to identify the exact path and status. Then check the document root, file existence, rewrite rules, and directory authorization. A 403 can result from Apache authorization rules or missing execute permission on one of the parent directories, not only from the file itself.

TLS warnings

Inspect the certificate presented with a TLS client. Compare its names with the requested hostname, check its expiry, verify the certificate chain, and confirm that the configured certificate and private key belong together. Also verify that the client is reaching the intended server and HTTPS virtual host.

Reverse-proxy 502 or 503 responses

Test the backend directly from the Apache host, such as with a local curl request. Confirm that the process is running, the address and port are correct, local firewall rules permit access, the proxy modules are loaded, and timeouts are appropriate. Apache's error log usually identifies connection refusal, DNS failure, or timeout details.

Forward-proxy abuse

Review proxy access rules and logs immediately. Restrict source networks, narrow CONNECT permissions, add authentication where appropriate, and disable forward proxying if it is unnecessary. An internet-accessible proxy with broad permissions is an open proxy and can be used to hide abuse.

server-status problems

If the endpoint is inaccessible, confirm that mod_status is loaded and that the Location authorization permits the administrator's address. If it is publicly accessible, fix the effective access rules, test from both authorized and unauthorized clients, and review whether another included fragment overrides the intended restriction.

Operational security and change management

  • Limit administrative endpoints such as server-status to trusted networks.
  • Use least-privilege ownership and permissions for content, logs, configuration, certificates, and private keys.
  • Never deploy an unrestricted forward proxy.
  • Back up configuration before edits and keep site-specific settings separate from global defaults.
  • Run a syntax check before reloads and use graceful reloads when suitable.
  • Rotate logs and protect retained client information.
  • After every change, test the intended hostname, protocol, path, status code, and log output.
  • Correlate mod_status observations with access logs, error logs, backend health, and system resource metrics.

Practical administration checklist

  1. Identify the distribution, service name, configuration includes, active modules, and log directories.
  2. Back up the configuration and create a focused site or module fragment.
  3. Check document-root ownership, read permissions, and directory traversal permissions.
  4. Validate the configuration with apachectl -t.
  5. Reload Apache and check service status.
  6. Test virtual-host routing with DNS, a hosts-file entry, or an explicit Host header.
  7. For HTTPS, verify certificate names, dates, chain, private-key protection, and the presented certificate.
  8. For proxying, test the backend or outbound policy from the correct client location.
  9. Inspect access and error logs after the change.
  10. Check restricted status information when investigating worker pressure or traffic changes.

Related administration topics include authentication and authorization, PHP-FPM integration, caching and compression, centralized logging, firewall configuration, web application firewalls, load balancing, automated certificate renewal, and performance tuning.