A Comprehensive Guide to Apache Web Server Configuration

This guide provides a complete walkthrough for installing, configuring, securing, and troubleshooting your Apache web server. We'll cover everything from the initial setup to hosting multiple websites with virtual hosts, securing your traffic with HTTPS, and allowing users to publish their own web content. Let's dive in!

Contents

1. What is the Apache Web Server?

Simply put, the Apache HTTPD (or just "Apache") is the most popular program that delivers web content (like web pages) to your browser.

It runs quietly in the background on your server as the httpd program. When you type a website address, your browser sends a request to Apache, and Apache sends the page back.

Why it's great:
  • It's free and open-source, supported by a massive community.
  • It works seamlessly on all major Linux systems, including Fedora, RHEL, and Ubuntu.
  • It's incredibly flexible. You can host multiple websites, secure communications, and implement various login methods.
  • It uses a powerful module system for extra features, like running Perl or PHP scripts, or adding SSL/TLS encryption.

A bit of history: Apache began as a series of improvements to the NCSA HTTPD web server. This effort evolved into the Apache Group and later the Apache Software Foundation (ASF), which now supports other major open-source projects like Tomcat and Hadoop.


2. Getting and Installing Apache

To get started, you'll need to install the necessary software packages on your Linux system. For a basic setup, you only need the httpd package.

What's in the httpd package?
  • The main Apache program: /usr/sbin/httpd
  • Key configuration files:
    • /etc/httpd/conf/httpd.conf: The main configuration file for your server.
    • /etc/httpd/conf.d/welcome.conf: Configures the default "Welcome" page.
    • /etc/httpd/conf.modules.d/*.conf: Loads additional modules for extended functionality.

Apache automatically reads any .conf files in the /etc/httpd/conf.d/ and /etc/httpd/conf.modules.d/ directories to load module-specific settings.

How to check package details (before installing):
  1. Download the package:
    # yumdownloader httpd
  2. View its information:
    # rpm -qpi httpd-*rpm
  3. See its configuration files:
    # rpm -qpc httpd-*rpm
Installing the "Web Server" Group (Recommended):

For a more complete setup with useful extras, install the "Web Server" group.

# yum groupinstall "Web Server"

This bundle includes httpd-manual (for documentation), mod_ssl (for HTTPS), crypto-utils, modules for Perl and PHP, squid (for proxy services), and webalizer (for traffic analysis).

You need an active internet connection for yum to download these packages.


3. Starting Apache

Once installed, you need to start the Apache service and enable it to launch automatically on boot.

For modern Linux (Fedora 30, RHEL 8):
  1. Enable on reboot:
    # systemctl enable httpd.service
  2. Start now:
    # systemctl start httpd.service
  3. Check status:
    # systemctl status httpd.service
For older Linux (RHEL 6 and below):
  1. # chkconfig httpd on
  2. # service httpd start
Debugging Apache:

To get more detailed logs for troubleshooting, you can edit the httpd service to run in debug mode.

  1. # systemctl edit httpd
  2. Under [Service], add: Environment=OPTIONS='-e debug'
  3. Save, exit, and restart Apache.

Important: Remove the -e debug option once you're done troubleshooting. Otherwise, your log files will grow very large, very quickly!


4. Securing Apache

Protecting your web server is crucial. This involves standard Linux security practices combined with Apache-specific settings.

File Permissions and Ownership

  • The httpd program runs as the apache user and apache group.
  • Your website content is stored in /var/www/html by default.
  • For Apache to serve your web pages, the apache user needs read permission on the files and execute permission on all parent directories.

Apache and Firewalls

If your firewall is active, you must open ports for web traffic.

  • HTTP: TCP port 80
  • HTTPS: TCP port 443 (if mod_ssl is installed)

Use the Firewall application or command-line tools to enable the http and https services for your public zone.

Apache and SELinux (Security Enhanced Linux)

SELinux adds a powerful layer of security, enabled by default in Fedora/RHEL. It protects your system even if Apache is compromised.

Tips for SELinux with Apache:
  • Read the manual: Run man httpd_selinux for detailed information.
  • Use standard locations: Storing content in /var/www/html automatically applies the correct SELinux labels.
  • Custom Locations: If you use non-standard directories, you must manually set the correct SELinux file contexts and Booleans to grant Apache access.

5. Understanding Apache Configuration Files

Apache's flexibility comes from its configuration directives. The main file is /etc/httpd/conf/httpd.conf, but settings are also loaded from files in /etc/httpd/conf.d/.

Configuration Blocks (<LocationTag>):
  • <Directory /path/to/folder>: Applies settings to a filesystem path.
  • <Files filename.ext>: Applies settings to specific files by name.
  • <Location /url/path>: Applies settings to a URL path, not a filesystem path.

You can also place small configuration files named .htaccess inside your web directories to override certain server settings. This is controlled by the AllowOverride directive in httpd.conf.


6. Understanding Default Apache Settings

Apache works out-of-the-box thanks to a set of sensible defaults in httpd.conf.

Key Default Settings:
  • ServerRoot: "/etc/httpd"
  • DocumentRoot: "/var/www/html"
  • Listen: 80 (listens on port 80 for all network interfaces)
  • User: apache
  • Group: apache
  • ErrorLog: logs/error_log
  • CustomLog: logs/access_log combined

By default, Apache denies access to the entire filesystem root (<Directory />) but then specifically allows access to /var/www and /var/www/html.


7. Adding a Virtual Host to Apache

Virtual hosts allow you to host multiple websites (e.g., example.com and example.org) on a single server.

Steps to create a Virtual Host:
  1. Create a new configuration file, such as /etc/httpd/conf.d/example.org.conf.
  2. Add the virtual host configuration block to the file:
    <VirtualHost *:80>
        ServerAdmin webmaster@example.org
        ServerName www.example.org
        ServerAlias web.example.org
        DocumentRoot /var/www/html/example.org/
        DirectoryIndex index.php index.html
    </VirtualHost>
  3. Crucial Note: Once you add your first virtual host, the main DocumentRoot is no longer used for unmatched requests. The first virtual host you define becomes the default for all requests that don't match another ServerName.

  4. Check and Restart Apache:
    # apachectl configtest
    # apachectl graceful
  5. Point your domain's DNS to your server's IP and test it in a browser.

8. Allowing Users to Publish Web Content

You can let users publish web pages from a public_html folder in their home directory. This content is accessible at http://your-server/~username/.

  1. Enable mod_userdir in httpd.conf:
    <IfModule mod_userdir.c>
        UserDir enabled
        UserDir public_html
    </IfModule>
  2. Allow access to user directories:
    <Directory "/home/*/public_html">
        Options Indexes Includes FollowSymLinks
        Require all granted
    </Directory>
  3. Set SELinux Boolean (if enforcing):
    # setsebool -P httpd_enable_homedirs true
  4. Reload Apache and test.

9. Securing Your Web Traffic with SSL/TLS (HTTPS)

Standard HTTP sends data in plain text. HTTPS uses SSL/TLS (Transport Layer Security) to encrypt the data, protecting it from eavesdroppers.

This is achieved using a private key on your server and a digital certificate that verifies your server's identity. For public websites, this certificate is signed by a trusted Certificate Authority (CA) like Let's Encrypt.


10. How SSL is Configured (and Testing the Default)

The mod_ssl package handles SSL/TLS for Apache. When installed, it creates a default self-signed certificate for immediate testing.

Key Settings in /etc/httpd/conf.d/ssl.conf:
  • Listen 443 https
  • SSLEngine on
  • SSLCertificateFile /etc/pki/tls/certs/localhost.crt
  • SSLCertificateKeyFile /etc/pki/tls/private/localhost.key
Testing the Default SSL Certificate:
  1. Open a web browser on the server.
  2. Navigate to https://localhost.
  3. You will see a "Potential Security Risk" warning. This is normal because the certificate is self-signed.
  4. Click "Advanced," view the certificate, and accept the risk to continue.

11. Creating Your Own SSL Key and Self-Signed Certificate

You can create your own key and certificate for internal use or as a first step toward getting a CA-signed certificate.

  1. Generate a Private Key:
    # cd /etc/pki/tls/private
    # openssl genrsa -out server.key 2048
    # chmod 600 server.key
  2. Generate a Self-Signed Certificate:
    # cd /etc/pki/tls/certs
    # openssl req -new -x509 -key ../private/server.key -out server.crt -days 365

    When prompted, ensure the "Common Name" matches your server's hostname or domain name.

  3. Update the SSLCertificateFile and SSLCertificateKeyFile directives in ssl.conf to point to your new files.
  4. Reload Apache.

12. Generating a Certificate Signing Request (CSR)

To get a certificate from a trusted CA, you must first generate a CSR.

  1. Create a CSR directory:
    # mkdir /etc/pki/tls/ssl.csr
    # cd /etc/pki/tls/ssl.csr/
  2. Generate the CSR:
    # openssl req -new -key ../private/server.key -out server.csr
  3. Copy the contents of the server.csr file and submit it to your chosen CA.
  4. Once you receive the signed certificate from the CA, save it in /etc/pki/tls/certs/ and update your SSLCertificateFile directive in ssl.conf.

13. Troubleshooting Your Web Server

When issues arise, here’s how to diagnose and fix them. The first step is always to check the error log at /var/log/httpd/error_log.

Configuration Errors (Syntax OK fails)

Always run apachectl configtest after making changes. If it fails, the error message will usually point to the exact line with the problem.

Address already in use (make_sock)

This means another process is already using port 80 or 443. Use netstat -nltp to find the conflicting program. Check for duplicate Listen directives in your configuration files.

File permissions prevent access (403 Forbidden)

This is a permissions issue. Ensure the apache user has read access to the file and execute access to all directories in its path. Also, check for SELinux denials.

Client denied by server configuration (403 Forbidden)

Your Apache configuration is explicitly blocking the request. Check your <Directory> and <Location> blocks for Require, Allow, or Deny rules that might be the cause.

Directory index forbidden by rule (403 Forbidden)

Apache cannot find a default file (like index.html) as defined by DirectoryIndex, and the Options Indexes directive is not set to allow a file listing.

Premature end of script headers (500 Internal Server Error)

A CGI or PHP script crashed before it could output valid headers. Check the script itself for errors and review the server's error log for more specific details.

SELinux is blocking access

If file permissions are correct but you still get a "permission denied" error, SELinux is likely the cause. Temporarily set it to permissive mode with setenforce 0 to confirm. If that works, you need to apply the correct SELinux file contexts (e.g., httpd_sys_content_t) or Booleans (e.g., httpd_can_network_connect).