BLOG POSTS
How to Install Apache Web Server on CentOS 8

How to Install Apache Web Server on CentOS 8

Setting up Apache HTTP Server on CentOS 8 is one of those essential skills that every sysadmin and developer should have in their toolkit. Apache remains the most widely used web server globally, powering roughly 35% of all websites, and CentOS 8 provides a rock-solid foundation for hosting web applications. In this comprehensive guide, you’ll learn how to install, configure, and optimize Apache on CentOS 8, along with troubleshooting common issues and implementing security best practices that’ll keep your server running smoothly in production environments.

How Apache Works on CentOS 8

Apache HTTP Server operates as a modular, process-based web server that handles HTTP requests through a multi-processing module (MPM). On CentOS 8, Apache uses the event MPM by default, which combines the stability of the prefork model with the performance benefits of threading. This architecture allows Apache to handle thousands of concurrent connections efficiently while maintaining process isolation.

The server reads configuration from multiple files located in /etc/httpd/, with the main configuration in /etc/httpd/conf/httpd.conf. CentOS 8 packages Apache with systemd integration, making service management straightforward through systemctl commands. The default document root is /var/www/html, and log files are stored in /var/log/httpd/.

Prerequisites and System Preparation

Before diving into the installation, ensure your CentOS 8 system is updated and ready. You’ll need root or sudo privileges, and at least 512MB of RAM (though 1GB+ is recommended for production use).

# Update system packages
sudo dnf update -y

# Check CentOS version
cat /etc/centos-release

# Verify available disk space (should have at least 2GB free)
df -h

# Check if port 80 and 443 are available
sudo netstat -tuln | grep -E ':80|:443'

Step-by-Step Apache Installation Guide

CentOS 8 uses DNF as the default package manager, making Apache installation straightforward. Here’s the complete process:

Install Apache HTTP Server

# Install Apache web server
sudo dnf install httpd -y

# Verify installation
httpd -v

# Check installed modules
httpd -M

Configure Firewall Rules

CentOS 8 comes with firewalld enabled by default, so you’ll need to open HTTP and HTTPS ports:

# Check firewall status
sudo firewall-cmd --state

# Add HTTP service (port 80)
sudo firewall-cmd --permanent --add-service=http

# Add HTTPS service (port 443)
sudo firewall-cmd --permanent --add-service=https

# Reload firewall configuration
sudo firewall-cmd --reload

# Verify rules
sudo firewall-cmd --list-services

Start and Enable Apache Service

# Start Apache service
sudo systemctl start httpd

# Enable Apache to start on boot
sudo systemctl enable httpd

# Check service status
sudo systemctl status httpd

# Verify Apache is listening on port 80
sudo ss -tuln | grep :80

Initial Configuration and Testing

Once Apache is running, test the installation by accessing your server’s IP address. You should see the default CentOS Apache test page.

# Find your server's IP address
ip addr show

# Test local connectivity
curl localhost

# Create a simple test page
sudo echo "

Apache on CentOS 8 - Working!

" > /var/www/html/index.html # Set proper permissions sudo chown apache:apache /var/www/html/index.html sudo chmod 644 /var/www/html/index.html

Essential Apache Configuration

The main Apache configuration file is located at /etc/httpd/conf/httpd.conf. Here are the key settings you should review and customize:

# Backup original configuration
sudo cp /etc/httpd/conf/httpd.conf /etc/httpd/conf/httpd.conf.backup

# Edit main configuration
sudo vi /etc/httpd/conf/httpd.conf

Key Configuration Directives

# Server identification
ServerTokens Prod
ServerSignature Off

# Performance tuning
ServerLimit 10
MaxRequestWorkers 400
ThreadsPerChild 40

# Security headers
Header always set X-Content-Type-Options nosniff
Header always set X-Frame-Options DENY
Header always set X-XSS-Protection "1; mode=block"

# Document root
DocumentRoot "/var/www/html"

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

Virtual Hosts Configuration

Virtual hosts allow you to serve multiple websites from a single Apache instance. Create virtual host configurations in /etc/httpd/conf.d/:

# Create virtual host configuration
sudo vi /etc/httpd/conf.d/example.com.conf
<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/html/example.com
    
    ErrorLog /var/log/httpd/example.com_error.log
    CustomLog /var/log/httpd/example.com_access.log combined
    
    <Directory "/var/www/html/example.com">
        Options -Indexes +FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>
# Create document directory
sudo mkdir -p /var/www/html/example.com

# Set ownership and permissions
sudo chown -R apache:apache /var/www/html/example.com
sudo chmod -R 755 /var/www/html/example.com

# Test configuration
sudo httpd -t

# Reload Apache
sudo systemctl reload httpd

Security Hardening Best Practices

Securing Apache is crucial for production deployments. Here are essential security configurations:

Hide Apache Version Information

# Add to /etc/httpd/conf/httpd.conf
ServerTokens Prod
ServerSignature Off

Disable Unnecessary Modules

# List loaded modules
httpd -M

# Comment out unused modules in /etc/httpd/conf.modules.d/
# For example, disable autoindex if not needed
# LoadModule autoindex_module modules/mod_autoindex.so

Configure SSL/TLS (Recommended)

# Install SSL module
sudo dnf install mod_ssl -y

# Generate self-signed certificate (for testing)
sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
-keyout /etc/pki/tls/private/apache-selfsigned.key \
-out /etc/pki/tls/certs/apache-selfsigned.crt

Performance Optimization

Apache performance can be significantly improved through proper configuration and caching mechanisms:

Configuration Parameter Default Value Recommended Value Description
MaxRequestWorkers 256 400-800 Maximum concurrent connections
ThreadsPerChild 25 40-80 Number of threads per child process
KeepAliveTimeout 5 2-5 Seconds to wait for next request
MaxKeepAliveRequests 100 500 Maximum requests per connection

Enable Compression

# Enable mod_deflate for compression
sudo vi /etc/httpd/conf.d/compression.conf
LoadModule deflate_module modules/mod_deflate.so

<Location "/">
    SetOutputFilter DEFLATE
    
    # Don't compress images, videos, or archives
    SetEnvIfNoCase Request_URI \
        \.(?:gif|jpe?g|png|zip|gz|tgz|bz2|tbz|mp3|mp4|avi)$ no-gzip dont-vary
    
    # Don't compress very small files
    SetEnvIf Content-Length 0 no-gzip
</Location>

Common Issues and Troubleshooting

Here are the most frequent problems you’ll encounter and their solutions:

Apache Won’t Start

# Check for configuration errors
sudo httpd -t

# View detailed error logs
sudo journalctl -u httpd.service -f

# Check for port conflicts
sudo netstat -tulpn | grep :80

# Verify SELinux context
sudo setsebool -P httpd_can_network_connect 1

Permission Denied Errors

# Check file permissions
ls -la /var/www/html/

# Fix ownership
sudo chown -R apache:apache /var/www/html/

# Set proper SELinux context
sudo restorecon -R /var/www/html/

403 Forbidden Errors

# Check directory permissions
sudo chmod 755 /var/www/html/

# Verify Apache configuration
grep -R "Require" /etc/httpd/conf.d/

# Check for .htaccess issues
sudo find /var/www/html/ -name ".htaccess" -exec cat {} \;

Apache vs. Alternatives Comparison

Feature Apache HTTP Server Nginx Lighttpd
Memory Usage Moderate (20-40MB) Low (10-20MB) Very Low (5-15MB)
Concurrent Connections 1,000-5,000 10,000+ 5,000-10,000
.htaccess Support Full Support None (config reload needed) Limited
Module Ecosystem Extensive Moderate Limited
Configuration Complexity Moderate Low Low

Real-World Use Cases and Applications

Apache on CentOS 8 excels in several scenarios:

  • WordPress Hosting: Apache’s .htaccess support makes it ideal for WordPress sites requiring URL rewriting and custom redirects
  • Development Environments: Easy virtual host configuration allows developers to host multiple projects locally
  • Legacy Application Support: Extensive module ecosystem supports older PHP applications and custom authentication systems
  • Mixed Content Serving: Apache handles both static and dynamic content efficiently with proper caching modules
  • SSL/TLS Termination: Robust SSL implementation with support for modern cipher suites and HTTP/2

Production Deployment Example

# Production-ready virtual host with security headers
<VirtualHost *:443>
    ServerName production.example.com
    DocumentRoot /var/www/html/production
    
    SSLEngine on
    SSLCertificateFile /etc/pki/tls/certs/production.crt
    SSLCertificateKeyFile /etc/pki/tls/private/production.key
    
    # Security headers
    Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"
    Header always set Content-Security-Policy "default-src 'self'"
    
    # Logging
    ErrorLog /var/log/httpd/production_error.log
    CustomLog /var/log/httpd/production_access.log combined
    
    # Performance
    ExpiresActive On
    ExpiresByType text/css "access plus 1 month"
    ExpiresByType application/javascript "access plus 1 month"
</VirtualHost>

Monitoring and Maintenance

Keeping Apache healthy requires regular monitoring and maintenance:

# Monitor Apache processes
ps aux | grep httpd

# Check memory usage
free -h

# Monitor access logs in real-time
sudo tail -f /var/log/httpd/access_log

# Generate Apache status report (requires mod_status)
curl http://localhost/server-status

# Set up log rotation (usually automatic)
sudo logrotate -f /etc/logrotate.d/httpd

Performance Monitoring Script

#!/bin/bash
# apache_monitor.sh

echo "=== Apache Status Monitor ==="
echo "Active Connections: $(ss -tuln | grep :80 | wc -l)"
echo "Apache Processes: $(pgrep httpd | wc -l)"
echo "Memory Usage: $(ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%mem | grep httpd | head -1 | awk '{print $4"%"}')"
echo "Last 10 Error Log Entries:"
tail -10 /var/log/httpd/error_log

For comprehensive server management and hosting solutions, consider exploring VPS services or dedicated servers that come pre-configured with optimized Apache installations.

Apache HTTP Server on CentOS 8 provides a robust foundation for web hosting, combining proven stability with modern performance features. The extensive module ecosystem and flexible configuration options make it suitable for everything from simple static sites to complex web applications. Regular maintenance, security updates, and performance monitoring will ensure your Apache installation continues to serve your needs reliably in production environments.

For additional information and advanced configuration options, refer to the official Apache HTTP Server documentation and the CentOS installation guide.



This article incorporates information and material from various online sources. We acknowledge and appreciate the work of all original authors, publishers, and websites. While every effort has been made to appropriately credit the source material, any unintentional oversight or omission does not constitute a copyright infringement. All trademarks, logos, and images mentioned are the property of their respective owners. If you believe that any content used in this article infringes upon your copyright, please contact us immediately for review and prompt action.

This article is intended for informational and educational purposes only and does not infringe on the rights of the copyright owners. If any copyrighted material has been used without proper credit or in violation of copyright laws, it is unintentional and we will rectify it promptly upon notification. Please note that the republishing, redistribution, or reproduction of part or all of the contents in any form is prohibited without express written permission from the author and website owner. For permissions or further inquiries, please contact us.

Leave a reply

Your email address will not be published. Required fields are marked