Lessons

Apache2 Web Server

Level: Intermediate Module: Web Services 8 min read Lesson 22 of 66

Overview

  • What you’ll learn: How to install Apache2 on Ubuntu, manage its service, configure virtual hosts, enable modules, set up access control, and tune performance.
  • Prerequisites: Lesson 21 — HTTP Protocol Fundamentals
  • Estimated reading time: 18 minutes

Introduction

Apache HTTP Server (commonly called Apache or Apache2) is one of the oldest and most widely used web servers in the world. First released in 1995, it has powered a significant portion of the Internet for over two decades. Apache’s popularity stems from its stability, extensive module ecosystem, and flexible configuration system.

On Ubuntu, the Apache2 package is maintained in the official repositories and is straightforward to install and configure. Apache uses a modular architecture — core functionality is provided by the server itself, and additional features such as SSL/TLS support, URL rewriting, and authentication are added through loadable modules.

In this lesson, you will learn how to install Apache2, understand its directory structure and configuration files, set up name-based virtual hosts to serve multiple websites from a single server, enable and disable modules, configure access control, and apply basic performance tuning.

Installing Apache2

Apache2 is available in the Ubuntu default repositories. Install it using APT:

# Update package index and install Apache2
$ sudo apt update
$ sudo apt install apache2

# Verify the installation
$ apache2 -v
Server version: Apache/2.4.52 (Ubuntu)

# Check service status
$ sudo systemctl status apache2
● apache2.service - The Apache HTTP Server
     Loaded: loaded (/lib/systemd/system/apache2.service; enabled)
     Active: active (running)

After installation, Apache starts automatically and listens on port 80. You can verify by opening http://your-server-ip/ in a browser or using curl:

$ curl -I http://localhost/
HTTP/1.1 200 OK
Server: Apache/2.4.52 (Ubuntu)

Directory Structure and Configuration Files

Apache2 on Ubuntu follows the Debian-style configuration layout, which splits the configuration across multiple directories for clarity and maintainability:

/etc/apache2/
├── apache2.conf          # Main configuration file
├── envvars               # Environment variables (user, group, etc.)
├── ports.conf            # Listening ports
├── conf-available/       # Available configuration snippets
├── conf-enabled/         # Enabled configuration snippets (symlinks)
├── mods-available/       # Available modules
├── mods-enabled/         # Enabled modules (symlinks)
├── sites-available/      # Available virtual host definitions
└── sites-enabled/        # Enabled virtual hosts (symlinks)

Key files include:

  • apache2.conf: The main configuration file. It includes directives for server-wide settings and pulls in other configuration files.
  • ports.conf: Defines which ports Apache listens on (default: 80 for HTTP, 443 for HTTPS).
  • sites-available/000-default.conf: The default virtual host configuration.
  • envvars: Sets environment variables such as APACHE_RUN_USER and APACHE_RUN_GROUP.
# View the main configuration file
$ cat /etc/apache2/apache2.conf | grep -v "^#" | grep -v "^$"

# View listening ports
$ cat /etc/apache2/ports.conf
Listen 80
<IfModule ssl_module>
    Listen 443
</IfModule>

Virtual Hosts

Virtual hosts allow Apache to serve multiple websites from a single server. The most common type is name-based virtual hosting, where the server uses the HTTP Host header to determine which site to serve.

Creating a Virtual Host

# Create a document root for the site
$ sudo mkdir -p /var/www/example.com/public_html
$ echo "<h1>Welcome to example.com</h1>" | sudo tee /var/www/example.com/public_html/index.html

# Set proper ownership
$ sudo chown -R www-data:www-data /var/www/example.com

# Create the virtual host configuration
$ sudo nano /etc/apache2/sites-available/example.com.conf

Add the following configuration:

<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/example.com/public_html
    ServerAdmin webmaster@example.com

    ErrorLog ${APACHE_LOG_DIR}/example.com-error.log
    CustomLog ${APACHE_LOG_DIR}/example.com-access.log combined

    <Directory /var/www/example.com/public_html>
        Options -Indexes +FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

Enabling and Managing Virtual Hosts

# Enable the site
$ sudo a2ensite example.com.conf
Enabling site example.com.

# Disable the default site (optional)
$ sudo a2dissite 000-default.conf

# Test configuration syntax
$ sudo apache2ctl configtest
Syntax OK

# Reload Apache to apply changes
$ sudo systemctl reload apache2

Apache Modules

Apache’s modular architecture allows you to enable only the features you need. Common modules include:

  • mod_rewrite: URL rewriting rules (used by WordPress, Laravel, etc.).
  • mod_ssl: TLS/SSL support for HTTPS.
  • mod_headers: Custom HTTP response headers.
  • mod_proxy: Forward and reverse proxy functionality.
  • mod_deflate: Response compression (gzip).
  • mod_security2: Web application firewall (WAF).
# List enabled modules
$ apache2ctl -M

# Enable a module
$ sudo a2enmod rewrite
Enabling module rewrite.

# Enable SSL module
$ sudo a2enmod ssl

# Disable a module
$ sudo a2dismod autoindex

# Restart Apache after module changes
$ sudo systemctl restart apache2

mod_rewrite Example

A common use case is rewriting all requests to a front controller (e.g., for PHP frameworks):

# /var/www/example.com/public_html/.htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?$1 [L,QSA]

Access Control

Apache 2.4 uses the Require directive for access control, replacing the older Order/Allow/Deny syntax:

# Allow all access
<Directory /var/www/public>
    Require all granted
</Directory>

# Deny all access
<Directory /var/www/private>
    Require all denied
</Directory>

# Allow specific IP range only
<Directory /var/www/admin>
    Require ip 192.168.1.0/24
    Require ip 10.0.0.0/8
</Directory>

# Basic authentication
<Directory /var/www/protected>
    AuthType Basic
    AuthName "Restricted Area"
    AuthUserFile /etc/apache2/.htpasswd
    Require valid-user
</Directory>
# Create an htpasswd file
$ sudo htpasswd -c /etc/apache2/.htpasswd admin
New password: ****
Re-type new password: ****

Performance Tuning

Apache’s default Multi-Processing Module (MPM) on Ubuntu is mpm_event, which is efficient for handling concurrent connections. Key tuning parameters include:

# /etc/apache2/mods-available/mpm_event.conf
<IfModule mpm_event_module>
    StartServers             2
    MinSpareThreads         25
    MaxSpareThreads         75
    ThreadLimit             64
    ThreadsPerChild         25
    MaxRequestWorkers      150
    MaxConnectionsPerChild   0
</IfModule>

Additional performance tips:

# Enable compression
$ sudo a2enmod deflate

# Enable caching headers
$ sudo a2enmod expires
$ sudo a2enmod headers

# Disable unnecessary modules to reduce memory usage
$ sudo a2dismod status
$ sudo a2dismod autoindex

# Check current MPM
$ apache2ctl -V | grep MPM
Server MPM:     event

# Monitor Apache processes
$ ps aux | grep apache2 | wc -l
$ sudo apache2ctl fullstatus   # requires mod_status

Logging

Apache provides two main log files by default:

# Access log — records all incoming requests
$ sudo tail -f /var/log/apache2/access.log
192.168.1.100 - - [15/Jan/2025:10:30:45 +0000] "GET / HTTP/1.1" 200 3456

# Error log — records server errors and diagnostics
$ sudo tail -f /var/log/apache2/error.log

# Per-site logs (as defined in virtual host)
$ sudo tail -f /var/log/apache2/example.com-access.log

Key Takeaways

  • Apache2 is installed with sudo apt install apache2 and starts automatically on port 80.
  • Ubuntu uses a Debian-style split configuration with sites-available/sites-enabled and mods-available/mods-enabled.
  • Name-based virtual hosts allow serving multiple websites from a single IP using the Host header.
  • Use a2ensite/a2dissite to manage virtual hosts and a2enmod/a2dismod to manage modules.
  • Always run apache2ctl configtest before reloading configuration to catch syntax errors.
  • Apache 2.4 uses the Require directive for access control.
  • The mpm_event MPM provides efficient handling of concurrent connections.

What’s Next

In Lesson 23, you will learn how to install and configure Nginx — a high-performance web server and reverse proxy. You will compare Nginx’s event-driven architecture with Apache’s process-based model and learn when to choose each server.

繁體中文

概述

  • 您將學到: 如何在 Ubuntu 上安裝 Apache2、管理其服務、設定虛擬主機、啟用模組、設定存取控制和調整效能。
  • 先決條件: 第 21 課 — HTTP 協定基礎
  • 預估閱讀時間: 18 分鐘

簡介

Apache HTTP Server(通常稱為 Apache 或 Apache2)是世界上最古老、使用最廣泛的網頁伺服器之一。Apache 的流行源於其穩定性、廣泛的模組生態系統和靈活的設定系統。

在 Ubuntu 上,Apache2 套件在官方儲存庫中維護,安裝和設定都很簡便。Apache 使用模組化架構——核心功能由伺服器本身提供,額外功能(如 SSL/TLS 支援、URL 重寫和認證)透過可載入模組添加。

安裝 Apache2

# 更新套件索引並安裝 Apache2
$ sudo apt update
$ sudo apt install apache2

# 驗證安裝
$ apache2 -v

# 檢查服務狀態
$ sudo systemctl status apache2

目錄結構和設定檔

/etc/apache2/
├── apache2.conf          # 主設定檔
├── envvars               # 環境變數
├── ports.conf            # 監聽埠
├── sites-available/      # 可用的虛擬主機定義
├── sites-enabled/        # 已啟用的虛擬主機(符號連結)
├── mods-available/       # 可用的模組
└── mods-enabled/         # 已啟用的模組(符號連結)

虛擬主機

虛擬主機允許 Apache 從單一伺服器提供多個網站。最常見的類型是基於名稱的虛擬主機,伺服器使用 HTTP Host 標頭來決定提供哪個網站。

<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/example.com/public_html
    ErrorLog ${APACHE_LOG_DIR}/example.com-error.log
    CustomLog ${APACHE_LOG_DIR}/example.com-access.log combined
</VirtualHost>
# 啟用網站
$ sudo a2ensite example.com.conf

# 測試設定語法
$ sudo apache2ctl configtest

# 重新載入 Apache
$ sudo systemctl reload apache2

Apache 模組

  • mod_rewrite: URL 重寫規則。
  • mod_ssl: TLS/SSL 支援。
  • mod_headers: 自訂 HTTP 回應標頭。
  • mod_proxy: 正向和反向代理功能。
  • mod_deflate: 回應壓縮(gzip)。
# 啟用模組
$ sudo a2enmod rewrite
$ sudo a2enmod ssl

# 停用模組
$ sudo a2dismod autoindex

# 重新啟動 Apache
$ sudo systemctl restart apache2

存取控制

# 允許所有存取
<Directory /var/www/public>
    Require all granted
</Directory>

# 僅允許特定 IP
<Directory /var/www/admin>
    Require ip 192.168.1.0/24
</Directory>

# 基本認證
$ sudo htpasswd -c /etc/apache2/.htpasswd admin

效能調整

Ubuntu 上 Apache 的預設多處理模組是 mpm_event,適合處理高併發連線。

# 啟用壓縮和快取標頭
$ sudo a2enmod deflate
$ sudo a2enmod expires
$ sudo a2enmod headers

重點整理

  • 使用 sudo apt install apache2 安裝 Apache2,自動在 80 埠啟動。
  • Ubuntu 使用 Debian 風格的分離設定,包含 sites-available/sites-enabled 和 mods-available/mods-enabled。
  • 使用 a2ensite/a2dissite 管理虛擬主機,a2enmod/a2dismod 管理模組。
  • 始終在重新載入設定前執行 apache2ctl configtest
  • Apache 2.4 使用 Require 指令進行存取控制。

下一步

在第 23 課中,您將學習如何安裝和設定 Nginx——一個高效能的網頁伺服器和反向代理。

日本語

概要

  • 学習内容: Ubuntu での Apache2 のインストール、サービス管理、バーチャルホスト設定、モジュール有効化、アクセス制御、パフォーマンスチューニング。
  • 前提条件: レッスン 21 — HTTP プロトコルの基礎
  • 推定読了時間: 18 分

はじめに

Apache HTTP Server(一般に Apache または Apache2 と呼ばれる)は、世界で最も古く、広く使用されているウェブサーバーの一つです。その人気は安定性、広範なモジュールエコシステム、柔軟な設定システムに由来します。

Ubuntu では、Apache2 パッケージは公式リポジトリで管理されており、インストールと設定が簡単です。Apache はモジュラーアーキテクチャを使用し、コア機能はサーバー自体が提供し、SSL/TLS サポート、URL リライト、認証などの追加機能はロード可能なモジュールで追加されます。

Apache2 のインストール

# パッケージインデックスを更新して Apache2 をインストール
$ sudo apt update
$ sudo apt install apache2

# インストールの確認
$ apache2 -v

# サービス状態の確認
$ sudo systemctl status apache2

ディレクトリ構造と設定ファイル

/etc/apache2/
├── apache2.conf          # メイン設定ファイル
├── envvars               # 環境変数
├── ports.conf            # リスニングポート
├── sites-available/      # 利用可能なバーチャルホスト定義
├── sites-enabled/        # 有効なバーチャルホスト(シンボリックリンク)
├── mods-available/       # 利用可能なモジュール
└── mods-enabled/         # 有効なモジュール(シンボリックリンク)

バーチャルホスト

バーチャルホストにより、Apache は単一のサーバーから複数のウェブサイトを提供できます。最も一般的なタイプは名前ベースのバーチャルホスティングです。

<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/example.com/public_html
    ErrorLog ${APACHE_LOG_DIR}/example.com-error.log
    CustomLog ${APACHE_LOG_DIR}/example.com-access.log combined
</VirtualHost>
# サイトを有効化
$ sudo a2ensite example.com.conf

# 設定構文をテスト
$ sudo apache2ctl configtest

# Apache をリロード
$ sudo systemctl reload apache2

Apache モジュール

  • mod_rewrite: URL リライトルール。
  • mod_ssl: TLS/SSL サポート。
  • mod_headers: カスタム HTTP レスポンスヘッダー。
  • mod_proxy: フォワードおよびリバースプロキシ機能。
  • mod_deflate: レスポンス圧縮(gzip)。
# モジュールを有効化
$ sudo a2enmod rewrite
$ sudo a2enmod ssl

# モジュールを無効化
$ sudo a2dismod autoindex

# Apache を再起動
$ sudo systemctl restart apache2

アクセス制御

# すべてのアクセスを許可
<Directory /var/www/public>
    Require all granted
</Directory>

# 特定の IP のみ許可
<Directory /var/www/admin>
    Require ip 192.168.1.0/24
</Directory>

# 基本認証
$ sudo htpasswd -c /etc/apache2/.htpasswd admin

パフォーマンスチューニング

Ubuntu での Apache のデフォルト MPM は mpm_event で、並行接続の処理に効率的です。

重要ポイント

  • sudo apt install apache2 で Apache2 をインストール、ポート 80 で自動起動。
  • Ubuntu は sites-available/sites-enabled と mods-available/mods-enabled の Debian スタイル設定を使用。
  • a2ensite/a2dissite でバーチャルホスト管理、a2enmod/a2dismod でモジュール管理。
  • 設定リロード前に必ず apache2ctl configtest を実行。
  • Apache 2.4 は Require ディレクティブでアクセス制御を行う。

次のステップ

レッスン 23 では、高性能ウェブサーバーおよびリバースプロキシである Nginx のインストールと設定方法を学びます。

You Missed