BLOG POSTS
    MangoHost Blog / How to Install the Apache Web Server on latest CentOS
How to Install the Apache Web Server on latest CentOS

How to Install the Apache Web Server on latest CentOS

Apache HTTP Server remains the most widely deployed web server globally, powering over 30% of all active websites according to Netcraft’s latest survey. For CentOS users, installing Apache provides a robust, battle-tested foundation for hosting everything from simple static sites to complex web applications. This guide walks you through the complete installation process on the latest CentOS releases, covering package management approaches, initial configuration, security hardening, and troubleshooting common deployment issues you’ll inevitably encounter in production environments.

Understanding Apache on CentOS: Package Sources and Versions

CentOS typically ships with Apache HTTP Server through the httpd package in its default repositories. The naming can trip up newcomers – while most distributions call it “apache2”, Red Hat-based systems use “httpd” for historical reasons. CentOS 8 and later versions include Apache 2.4.x, which brings significant performance improvements over the 2.2 branch, including better memory utilization, enhanced SSL/TLS support, and improved handling of concurrent connections.

The default CentOS repositories prioritize stability over bleeding-edge features, so you’ll typically get well-tested versions that lag behind upstream releases by several months. For most production deployments, this trade-off favors reliability over having the absolute latest features.

CentOS Version Default Apache Version Notable Features PHP Compatibility
CentOS 7 2.4.6+ Event MPM, HTTP/2 support PHP 5.4-8.x
CentOS 8 2.4.37+ Improved HTTP/2, better SSL PHP 7.2-8.x
CentOS Stream 9 2.4.51+ Enhanced security, performance PHP 8.0+

Step-by-Step Installation Process

Let’s dive into the actual installation. I’ll cover both the standard repository approach and alternative methods for specific use cases.

Method 1: Standard YUM/DNF Installation

First, update your system packages to ensure compatibility:

sudo yum update -y
# For CentOS 8+ use: sudo dnf update -y

Install Apache HTTP Server:

sudo yum install httpd -y
# For CentOS 8+: sudo dnf install httpd -y

Start and enable the Apache service:

sudo systemctl start httpd
sudo systemctl enable httpd

Verify the installation:

sudo systemctl status httpd
httpd -v

Configure firewall rules to allow HTTP and HTTPS traffic:

sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload

Method 2: Installing from Source (Advanced Users)

Sometimes you need specific compile-time options or the latest Apache version. Here’s how to build from source:

# Install development tools
sudo yum groupinstall "Development Tools" -y
sudo yum install pcre-devel zlib-devel openssl-devel -y

# Download and compile Apache
cd /tmp
wget https://archive.apache.org/dist/httpd/httpd-2.4.54.tar.gz
tar -xzf httpd-2.4.54.tar.gz
cd httpd-2.4.54

./configure --prefix=/etc/httpd \
            --enable-so \
            --enable-ssl \
            --enable-rewrite \
            --enable-http2 \
            --with-mpm=event

make && sudo make install

Initial Configuration and Testing

After installation, Apache’s main configuration file lives at /etc/httpd/conf/httpd.conf. The default setup works for basic testing, but you’ll want to customize several settings for production use.

Test your installation by navigating to your server’s IP address in a browser. You should see the Apache test page. If you’re working on a local VM or don’t know your IP:

ip addr show | grep inet

The default document root is /var/www/html. Create a simple test page:

sudo echo "<h1>Apache is working!</h1>" > /var/www/html/index.html
sudo chown apache:apache /var/www/html/index.html

Essential Configuration Tweaks

Edit the main configuration file:

sudo vim /etc/httpd/conf/httpd.conf

Key settings to review and modify:

# Set your server name
ServerName your-domain.com:80

# Adjust worker limits based on your server specs
ServerLimit 10
MaxRequestWorkers 250
ThreadsPerChild 25

# Security headers
ServerTokens Prod
ServerSignature Off

# Enable compression
LoadModule deflate_module modules/mod_deflate.so

Restart Apache to apply changes:

sudo systemctl restart httpd

Real-World Configuration Examples

Here are some practical configuration scenarios you’ll encounter:

Virtual Hosts Setup

Most production environments serve multiple domains from a single Apache instance. Create a virtual host configuration:

sudo vim /etc/httpd/conf.d/mysite.conf
<VirtualHost *:80>
    ServerName mysite.com
    ServerAlias www.mysite.com
    DocumentRoot /var/www/mysite
    ErrorLog /var/log/httpd/mysite_error.log
    CustomLog /var/log/httpd/mysite_access.log combined
    
    <Directory /var/www/mysite>
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

Create the document root and set permissions:

sudo mkdir -p /var/www/mysite
sudo chown -R apache:apache /var/www/mysite
sudo chmod -R 755 /var/www/mysite

SSL/HTTPS Configuration

Install SSL module and generate certificates:

sudo yum install mod_ssl openssl -y

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

Configure SSL virtual host:

<VirtualHost *:443>
    ServerName mysite.com
    DocumentRoot /var/www/mysite
    
    SSLEngine on
    SSLCertificateFile /etc/ssl/certs/apache-selfsigned.crt
    SSLCertificateKeyFile /etc/ssl/private/apache-selfsigned.key
    
    # Modern SSL configuration
    SSLProtocol all -SSLv3 -TLSv1 -TLSv1.1
    SSLCipherSuite ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256
    SSLHonorCipherOrder off
    SSLSessionTickets off
</VirtualHost>

Performance Optimization and Best Practices

Apache’s performance heavily depends on choosing the right Multi-Processing Module (MPM) and tuning worker processes. Here’s what works well in different scenarios:

Use Case Recommended MPM Memory Usage Concurrent Connections
Static content, low traffic prefork High Low-Medium
Dynamic content, PHP prefork + mod_php Very High Low
Mixed content, modern apps event Low Very High
High-traffic production event + PHP-FPM Medium High

Enable useful modules for performance:

# Enable compression
echo "LoadModule deflate_module modules/mod_deflate.so" >> /etc/httpd/conf.modules.d/00-base.conf

# Enable caching
echo "LoadModule expires_module modules/mod_expires.so" >> /etc/httpd/conf.modules.d/00-base.conf

# Configure compression in main config
<Location "/">
    SetOutputFilter DEFLATE
    SetEnvIfNoCase Request_URI \
        \.(?:gif|jpe?g|png)$ no-gzip dont-vary
    SetEnvIfNoCase Request_URI \
        \.(?:exe|t?gz|zip|bz2|sit|rar)$ no-gzip dont-vary
</Location>

Common Issues and Troubleshooting

Every Apache deployment runs into predictable issues. Here are the most frequent problems and their solutions:

Permission Denied Errors

SELinux often blocks Apache from accessing files outside standard directories:

# Check SELinux status
sestatus

# Allow Apache to access custom directories
sudo setsebool -P httpd_read_user_content 1
sudo setsebool -P httpd_enable_homedirs 1

# Or set proper context for custom document roots
sudo setsebool -P httpd_unified 1
sudo restorecon -Rv /var/www/

Port Already in Use

Check what’s using port 80:

sudo netstat -tlnp | grep :80
sudo lsof -i :80

Apache Won’t Start

Check configuration syntax and error logs:

sudo httpd -t
sudo journalctl -u httpd.service
sudo tail -f /var/log/httpd/error_log

High Memory Usage

Monitor Apache processes and adjust worker settings:

# Check current processes
ps aux | grep httpd

# Monitor memory usage
sudo htop -p $(pgrep -d',' httpd)

Tune prefork MPM settings based on available RAM:

<IfModule mpm_prefork_module>
    StartServers 5
    MinSpareServers 5
    MaxSpareServers 10
    MaxRequestWorkers 150
    MaxConnectionsPerChild 3000
</IfModule>

Apache vs. Alternative Web Servers

Understanding when Apache makes sense versus alternatives helps with architecture decisions:

Server Best For Memory Usage Configuration Complexity Module Ecosystem
Apache Complex sites, .htaccess support Medium-High Medium Extensive
Nginx Static content, reverse proxy Low Low-Medium Limited
Lighttpd Embedded systems, simple sites Very Low Low Basic
Caddy Automatic HTTPS, modern apps Low Very Low Growing

Apache excels when you need extensive module support, per-directory configuration via .htaccess files, or complex URL rewriting. Its mature ecosystem and comprehensive documentation make it ideal for traditional web hosting environments.

Security Hardening Checklist

Production Apache installations require several security configurations:

  • Disable unnecessary modules to reduce attack surface
  • Hide server version information
  • Configure proper file permissions on configuration files
  • Enable security headers
  • Restrict access to sensitive directories
  • Keep Apache and modules updated

Essential security configurations:

# Hide server information
ServerTokens Prod
ServerSignature Off

# Disable dangerous HTTP methods
<LimitExcept GET POST HEAD>
    deny from all
</LimitExcept>

# Prevent access to .htaccess files
<Files ".ht*">
    Require all denied
</Files>

# 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"

Regular maintenance includes monitoring logs for suspicious activity and keeping your installation updated:

sudo yum update httpd -y
# Monitor access logs for unusual patterns
sudo tail -f /var/log/httpd/access_log | grep -E "(POST|PUT|DELETE)"

The Apache HTTP Server documentation at https://httpd.apache.org/docs/ provides comprehensive configuration references, while the CentOS documentation at https://docs.centos.org/ covers distribution-specific considerations. For ongoing learning, the Apache HTTP Server Project’s security tips at https://httpd.apache.org/docs/2.4/misc/security_tips.html offers valuable hardening guidance.



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