BLOG POSTS
    MangoHost Blog / How to Configure Apache Web Server on Ubuntu or Debian VPS
How to Configure Apache Web Server on Ubuntu or Debian VPS

How to Configure Apache Web Server on Ubuntu or Debian VPS

Apache web server remains one of the most widely deployed HTTP servers in the world, powering millions of websites from personal blogs to enterprise applications. If you’re managing a Ubuntu or Debian VPS, properly configuring Apache is essential for serving web content efficiently and securely. This guide walks you through the complete process of installing, configuring, and optimizing Apache on your VPS, covering everything from basic setup to advanced security hardening and performance tuning.

How Apache Web Server Works

Apache HTTP Server operates using a modular architecture that processes HTTP requests through various stages. When a client sends a request, Apache follows this flow:

  • Request arrives at the configured port (typically 80 for HTTP, 443 for HTTPS)
  • Apache determines which virtual host should handle the request based on hostname and port
  • The request passes through loaded modules for processing (authentication, rewriting, etc.)
  • Apache locates the requested resource using DocumentRoot and directory configurations
  • The server generates a response and sends it back to the client

Apache’s Multi-Processing Module (MPM) determines how the server handles concurrent connections. The three main MPMs are:

MPM Type Memory Usage Performance Best For
Prefork High Stable but slower PHP applications, legacy modules
Worker Medium Better than Prefork Mixed content, moderate traffic
Event Low Highest performance High-traffic sites, static content

Step-by-Step Apache Installation and Configuration

Let’s start with a fresh Ubuntu or Debian installation and build a production-ready Apache setup.

Initial System Preparation

Update your system packages first:

sudo apt update && sudo apt upgrade -y
sudo apt install curl wget vim ufw -y

Installing Apache

Install Apache and essential modules:

sudo apt install apache2 apache2-utils -y
sudo systemctl start apache2
sudo systemctl enable apache2

Verify the installation:

sudo systemctl status apache2
apache2 -v

You should see Apache running and version information displayed. The default Apache page will be accessible at your server’s IP address.

Essential Apache Modules

Enable commonly needed modules:

sudo a2enmod rewrite
sudo a2enmod ssl
sudo a2enmod headers
sudo a2enmod expires
sudo a2enmod deflate
sudo a2enmod security2
sudo systemctl restart apache2

Configuring Virtual Hosts

Create a directory structure for your website:

sudo mkdir -p /var/www/example.com/public_html
sudo mkdir -p /var/www/example.com/logs
sudo chown -R www-data:www-data /var/www/example.com/
sudo chmod -R 755 /var/www/

Create a virtual host configuration file:

sudo vim /etc/apache2/sites-available/example.com.conf

Add this configuration:

<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/example.com/public_html
    
    ErrorLog /var/www/example.com/logs/error.log
    CustomLog /var/www/example.com/logs/access.log combined
    
    <Directory /var/www/example.com/public_html>
        Options -Indexes +FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
    
    # 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"
    
    # Compression
    <IfModule mod_deflate.c>
        AddOutputFilterByType DEFLATE text/plain
        AddOutputFilterByType DEFLATE text/html
        AddOutputFilterByType DEFLATE text/xml
        AddOutputFilterByType DEFLATE text/css
        AddOutputFilterByType DEFLATE application/xml
        AddOutputFilterByType DEFLATE application/xhtml+xml
        AddOutputFilterByType DEFLATE application/rss+xml
        AddOutputFilterByType DEFLATE application/javascript
        AddOutputFilterByType DEFLATE application/x-javascript
    </IfModule>
</VirtualHost>

Enable the site and disable the default:

sudo a2ensite example.com.conf
sudo a2dissite 000-default.conf
sudo systemctl reload apache2

Test the configuration:

sudo apache2ctl configtest

SSL/TLS Configuration with Let’s Encrypt

Install Certbot for free SSL certificates:

sudo apt install snapd -y
sudo snap install core; sudo snap refresh core
sudo snap install --classic certbot
sudo ln -s /snap/bin/certbot /usr/bin/certbot

Obtain and configure SSL certificate:

sudo certbot --apache -d example.com -d www.example.com

Set up automatic renewal:

sudo crontab -e

Add this line:

0 12 * * * /usr/bin/certbot renew --quiet

Performance Optimization and Security Hardening

Apache Performance Tuning

Edit the main Apache configuration:

sudo vim /etc/apache2/apache2.conf

Add performance-oriented settings:

# Hide Apache version
ServerTokens Prod
ServerSignature Off

# Timeout settings
Timeout 60
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5

# MPM Event configuration (if using Event MPM)
<IfModule mpm_event_module>
    StartServers             2
    MinSpareThreads         25
    MaxSpareThreads         75
    ThreadLimit             64
    ThreadsPerChild         25
    MaxRequestWorkers      400
    MaxConnectionsPerChild   0
</IfModule>

Implementing ModSecurity

Install and configure ModSecurity for web application firewall protection:

sudo apt install libapache2-mod-security2 -y
sudo mv /etc/modsecurity/modsecurity.conf-recommended /etc/modsecurity/modsecurity.conf
sudo vim /etc/modsecurity/modsecurity.conf

Change SecRuleEngine to On:

SecRuleEngine On

Download OWASP Core Rule Set:

cd /tmp
wget https://github.com/coreruleset/coreruleset/archive/v3.3.2.tar.gz
tar -xvzf v3.3.2.tar.gz
sudo mv coreruleset-3.3.2 /etc/modsecurity/
sudo cp /etc/modsecurity/coreruleset-3.3.2/crs-setup.conf.example /etc/modsecurity/coreruleset-3.3.2/crs-setup.conf

Edit Apache security configuration:

sudo vim /etc/apache2/mods-available/security2.conf

Add the rule set:

IncludeOptional /etc/modsecurity/coreruleset-3.3.2/crs-setup.conf
IncludeOptional /etc/modsecurity/coreruleset-3.3.2/rules/*.conf

Real-World Use Cases and Examples

Multi-Domain Hosting Setup

For hosting multiple domains on a single server, create separate virtual host files:

# Site 1: blog.example.com
sudo vim /etc/apache2/sites-available/blog.example.com.conf

<VirtualHost *:80>
    ServerName blog.example.com
    DocumentRoot /var/www/blog.example.com/public_html
    ErrorLog /var/www/blog.example.com/logs/error.log
    CustomLog /var/www/blog.example.com/logs/access.log combined
</VirtualHost>

# Site 2: shop.example.com  
sudo vim /etc/apache2/sites-available/shop.example.com.conf

<VirtualHost *:80>
    ServerName shop.example.com
    DocumentRoot /var/www/shop.example.com/public_html
    ErrorLog /var/www/shop.example.com/logs/error.log
    CustomLog /var/www/shop.example.com/logs/access.log combined
</VirtualHost>

PHP Application Configuration

For PHP applications, install PHP and configure Apache:

sudo apt install php8.1 php8.1-mysql php8.1-curl php8.1-gd php8.1-mbstring php8.1-xml php8.1-zip -y

Create a PHP-specific virtual host:

<VirtualHost *:80>
    ServerName webapp.example.com
    DocumentRoot /var/www/webapp.example.com/public_html
    
    <Directory /var/www/webapp.example.com/public_html>
        Options -Indexes +FollowSymLinks
        AllowOverride All
        Require all granted
        
        # PHP configuration
        php_admin_value upload_max_filesize 64M
        php_admin_value post_max_size 64M
        php_admin_value memory_limit 256M
    </Directory>
    
    # Security for sensitive files
    <Files ~ "\.(?:htaccess|htpasswd|ini|log|sh)$">
        Require all denied
    </Files>
</VirtualHost>

Comparing Apache with Alternatives

Feature Apache Nginx LiteSpeed
Memory Usage Higher Lower Lowest
Configuration .htaccess support Centralized only .htaccess support
Module Ecosystem Extensive Limited Good
Static File Performance Good Excellent Excellent
Learning Curve Moderate Steeper Moderate

Common Issues and Troubleshooting

Port Already in Use

If Apache fails to start due to port conflicts:

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

Kill conflicting processes or change Apache ports in /etc/apache2/ports.conf.

Permission Denied Errors

Fix common permission issues:

sudo chown -R www-data:www-data /var/www/
sudo chmod -R 755 /var/www/
sudo setsebool -P httpd_can_network_connect 1  # If SELinux is enabled

High Memory Usage

Monitor Apache processes and adjust MPM settings:

sudo ps aux | grep apache2
sudo apache2ctl status

Reduce MaxRequestWorkers and adjust other MPM parameters based on available RAM.

SSL Certificate Issues

Test SSL configuration:

sudo apache2ctl configtest
openssl s_client -connect example.com:443 -servername example.com

Best Practices and Security Considerations

Regular Maintenance Tasks

Create a maintenance script:

#!/bin/bash
# apache_maintenance.sh

# Rotate logs
sudo logrotate -f /etc/logrotate.d/apache2

# Update system
sudo apt update && sudo apt upgrade -y

# Check Apache configuration
sudo apache2ctl configtest

# Monitor disk space
df -h /var/log/

# Check for security updates
sudo unattended-upgrades --dry-run

Monitoring and Logging

Configure comprehensive logging:

# In virtual host configuration
LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\" %D" combined_with_time
CustomLog /var/www/example.com/logs/access.log combined_with_time

Set up log analysis with tools like GoAccess:

sudo apt install goaccess -y
goaccess /var/www/example.com/logs/access.log -c

Firewall Configuration

Configure UFW for Apache:

sudo ufw allow 'Apache Full'
sudo ufw allow ssh
sudo ufw --force enable
sudo ufw status

For more advanced server management, consider upgrading to dedicated servers for high-traffic applications.

Advanced Configuration Examples

Load Balancing Configuration

Set up reverse proxy load balancing:

sudo a2enmod proxy
sudo a2enmod proxy_http
sudo a2enmod proxy_balancer
sudo a2enmod lbmethod_byrequests

Configure load balancer:

<VirtualHost *:80>
    ServerName loadbalancer.example.com
    
    ProxyPreserveHost On
    ProxyRequests Off
    
    <Proxy balancer://mycluster>
        BalancerMember http://192.168.1.10:8080
        BalancerMember http://192.168.1.11:8080
        ProxySet lbmethod=byrequests
    </Proxy>
    
    ProxyPass / balancer://mycluster/
    ProxyPassReverse / balancer://mycluster/
</VirtualHost>

Rate Limiting with mod_reqtimeout

sudo a2enmod reqtimeout
sudo vim /etc/apache2/mods-available/reqtimeout.conf

<IfModule mod_reqtimeout.c>
    RequestReadTimeout header=20-40,MinRate=500 body=20,MinRate=500
</IfModule>

This configuration provides a solid foundation for running Apache on Ubuntu or Debian VPS environments. Regular monitoring, security updates, and performance tuning will ensure your web server remains reliable and secure. For detailed information about specific modules and advanced configurations, consult the official Apache documentation and consider implementing additional monitoring solutions like Nagios or Zabbix for production environments.



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