Apache HTTP Server Practical Tutorial

As the first choice for getting started with Web development, the old open source server Apache HTTP Server (hereinafter referred to as Apache) still maintains more than 30% of the global market share due to its cross-platform, modular, stable and easy-to-use features. This article focuses on core scenarios commonly used by novices/small teams and uses streamlined steps and code to help you get started quickly.


1. Quick installation and startup

We cover the three most mainstream environments: Linux, Docker and Docker Compose (for easy unified management).

1.1 Linux native installation

Linux is Apache's golden partner. Different distributions only need to adjust the package manager.

Ubuntu/Debian system

# 更新源并安装
sudo apt update && sudo apt install -y apache2

# 核心操作
sudo systemctl start apache2    # 启动
sudo systemctl enable apache2   # 开机自启
sudo systemctl status apache2   # 检查状态
apache2 -v                       # 查看版本

CentOS/RHEL system

# 安装(CentOS8+/RHEL8+用dnf)
sudo dnf install -y httpd

# 核心操作
sudo systemctl start httpd
sudo systemctl enable httpd
sudo systemctl status httpd
httpd -v

After successful installation, access the server IP (port 80) and you will see Apache’s default welcome page!


1.2 Docker/Docker Compose one-click deployment

Suitable for local testing, development environment isolation, or quickly building a microservice gateway.

Docker single container

# 拉取官方最新镜像
docker pull httpd:latest

# 启动(挂载本地目录简化配置修改)
docker run -d \
  --name my-local-apache \
  -p 8080:80 \
  -p 8443:443 \
  -v $(pwd)/html:/usr/local/apache2/htdocs \
  -v $(pwd)/logs:/usr/local/apache2/logs \
  httpd:latest

Access after startuphttp://localhost:8080That’s it, localhtml/The files in the directory will be directly used as the content of the Web root directory.


2. Core basic configuration

The core configuration of Apache is divided into global configuration and virtual host configuration. The paths for Linux native and Docker deployment are different:

EnvironmentGlobal configuration pathVirtual host path (Ubuntu as an example)Docker configuration path after mounting
Ubuntu/Debian/etc/apache2/apache2.conf/etc/apache2/sites-available/Need to be mounted separately/usr/local/apache2/conf/

2.1 Key optimization of global configuration

There is no need to make major changes to the global configuration. Newbies only need to adjust these three places to improve security and ease of use:

# 1. 隐藏Apache版本号(防止攻击者利用已知漏洞)
ServerTokens Prod
ServerSignature Off

# 2. 启用 KeepAlive(减少TCP握手次数,提升静态资源加载速度)
KeepAlive On
MaxKeepAliveRequests 100  # 单次连接最多请求数
KeepAliveTimeout 5        # 空闲连接超时时间(秒)

# 3. 启用常用核心模块(后续配置会用到)
# Ubuntu/Debian用 a2enmod 命令更方便:a2enmod rewrite deflate headers ssl
LoadModule rewrite_module modules/mod_rewrite.so
LoadModule deflate_module modules/mod_deflate.so
LoadModule headers_module modules/mod_headers.so

2.2 Virtual host configuration (most commonly used!)

Virtual host allows one server to host multiple domain names/sites. We use Ubuntu as an example to configure HTTP basic virtual host.

Step 1: Create site directory and test files

# 为站点创建专属目录(建议按域名命名)
sudo mkdir -p /var/www/example.com/html
# 修改权限让Apache能访问
sudo chown -R www-data:www-data /var/www/example.com
# 创建测试首页
sudo nano /var/www/example.com/html/index.html

Test home page content:

<!DOCTYPE html>
<html>
<head><title>Hello Apache!</title></head>
<body><h1>Welcome to example.com!</h1></body>
</html>

Step 2: Write virtual host configuration

# 创建配置文件 /etc/apache2/sites-available/example.com.conf
<VirtualHost *:80>
    # 站点基础信息
    ServerName example.com
    ServerAlias www.example.com  # 别名,多个域名指向同一站点
    DocumentRoot /var/www/example.com/html

    # 目录权限与特性
    <Directory "/var/www/example.com/html">
        Options Indexes FollowSymLinks  # 允许列目录(可选,生产环境建议关Indexes)
        AllowOverride All                # 允许用 .htaccess 覆盖配置(SEO重写必备)
        Require all granted              # 允许所有人访问
    </Directory>

    # 日志配置(便于排查问题)
    ErrorLog ${APACHE_LOG_DIR}/example_error.log
    CustomLog ${APACHE_LOG_DIR}/example_access.log combined
</VirtualHost>

Step 3: Enable configuration and reboot

# 禁用默认的 000-default.conf(可选,生产环境建议禁用)
sudo a2dissite 000-default.conf
# 启用我们的新配置
sudo a2ensite example.com.conf
# 验证配置语法(重要!避免重启失败)
sudo apache2ctl configtest
# 语法没问题则优雅重启(不影响在线用户)
sudo systemctl reload apache2

3. Practical advanced configuration

3.1 Let's Encrypt Free SSL Certificate (Mandatory HTTPS)

HTTPS is now standard, and Let's Encrypt provides free 90-day auto-renewing certificates withcertbotTools are available with just one click.

Ubuntu installation and configuration

# 安装 certbot 和 Apache插件
sudo apt update && sudo apt install -y certbot python3-certbot-apache

# 一键获取证书并配置HTTPS(自动修改虚拟主机配置)
sudo certbot --apache -d example.com -d www.example.com

# 验证自动续期
sudo certbot renew --dry-run

implementcertbotYou will be prompted to enter your email address and agree to the agreement. Finally, you will be asked whether to force HTTP to jump to HTTPS. Select2: RedirectThat’s it!


3.2 URL rewriting (SEO friendly)

use.htaccessImplement URL beautification, such asarticle.php?id=123Change to/article/123

Step 1: Create in the site root directory.htaccess

sudo nano /var/www/example.com/html/.htaccess

Step 2: Write rewrite rules

RewriteEngine On

# 1. 强制HTTPS(如果certbot没配置成功可以手动加)
# RewriteCond %{HTTPS} off
# RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# 2. www跳转到非www(也可以反过来)
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

# 3. 隐藏PHP扩展名
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

# 4. SEO友好的文章链接
RewriteRule ^article/([0-9]+)/?$ article.php?id=$1 [L]

3.3 Gzip compression (improve loading speed)

Compressing HTML, CSS, JS and other text resources can reduce the transmission volume by 60%-80%. Add directly to the global configuration or virtual host configuration:

<IfModule mod_deflate.c>
    # 启用压缩
    AddOutputFilterByType DEFLATE text/plain text/html text/xml text/css
    AddOutputFilterByType DEFLATE application/xml application/xhtml+xml application/rss+xml
    AddOutputFilterByType DEFLATE application/javascript application/x-javascript application/json

    # 压缩级别(1-9,推荐6:速度和压缩率平衡)
    DeflateCompressionLevel 6
</IfModule>

4. Summary of best practices

  1. Security first: Hide the version number, force HTTPS, prohibit listing of the production environment directory, and use firewalls to restrict ports.
  2. Performance first: Enable KeepAlive, Gzip compression, and static resource caching (you can usemod_expiresAdd to.htaccessor virtual host).
  3. Standardized Management: The virtual host is named according to the domain name and the syntax is verified before configuration (apache2ctl configtest), graceful restart after deployment (systemctl reload apache2)。
  4. Log Monitoring: Check the error log regularly, usetail -fObserve traffic volume and abnormal requests in real time.

Although Apache does not have the high concurrency performance of Nginx, its modular architecture and rich documentation are more friendly to novices and are suitable for deploying small and medium-sized static sites, blogs or as a simple reverse proxy.