如何使用 Apache 构建安全且高性能的 Ubuntu Web 服务器(完整指南)

目次

1. 介绍

什么是 Ubuntu Web 服务器?

Web 服务器是一种通过互联网提供网站的系统。常见的 Web 服务器软件包括 Apache、Nginx 和 LiteSpeed,但在 Ubuntu 上使用最广泛的选项是 Apache
Ubuntu 轻量、稳定且开源,因此深受个人和企业的喜爱。它尤其适合运行 LAMP 环境(Linux、Apache、MySQL/MariaDB、PHP),为众多网站和应用提供动力。

本文适合的读者

本指南面向 首次搭建 Web 服务器的初学者。它将讲解如何在 Ubuntu 上启动 Web 服务器、安装 Apache、配置虚拟主机和 SSL 证书,以及实现优化和安全加固。

你将学到的内容

  • 如何在 Ubuntu 上构建 Web 服务器(安装和配置 Apache)
  • 如何设置虚拟主机并管理多个网站
  • 如何使用 Let’s Encrypt 安装 免费 SSL
  • 如何进行 安全加固和性能优化
  • 常见的故障排除步骤和解决方案

2. 安装 Ubuntu 并进行初始设置

所需系统规格

要将 Ubuntu 用作 Web 服务器,建议的 最低规格 如下:

ItemMinimum RequirementsRecommended Requirements
OSUbuntu 22.04 LTSUbuntu 22.04 LTS
CPU1GHz or higher2GHz or higher
Memory512MB2GB or higher
Storage10GB or more20GB or more
NetworkInternet connectionHigh-speed connection recommended

下载并安装 Ubuntu

Ubuntu 可从官方网站下载(https://ubuntu.com/download/server)。下载 ISO 文件后,可在 VirtualBox 或 VMware 等虚拟机 中安装,或在 专用服务器或 VPS 上安装。

安装步骤:

  1. 创建安装介质
  • USB 盘(使用 Rufus 等工具)
  • 在虚拟机中挂载 ISO 文件
  1. 按照安装向导进行
  • 选择首选语言
  • 验证网络连接
  • 设置用户名和密码
  • 安装 SSH 服务器(可选——也可以稍后再装)
  1. 安装完成后重启
  2. 登录并开始初始配置

基本初始设置

安装完成后,执行以下初始设置步骤。

  1. 更新所有软件包
    sudo apt update && sudo apt upgrade -y
    

→ 应用安全补丁并更新软件包。

  1. 设置时区
    sudo timedatectl set-timezone Asia/Tokyo
    

→ 将系统时间设置为日本标准时间(JST)。

  1. 启用防火墙
    sudo ufw enable
    

→ 启动防火墙以防止未授权访问系统。

  1. 配置 SSH(用于远程管理)
  • 检查 SSH 是否已启用 sudo systemctl status ssh
  • 若未启用,使用 sudo systemctl enable --now ssh 启用

完成上述步骤后,你的 Ubuntu 服务器已准备好作为功能完整的 Web 服务器进行后续配置。

3. 安装与配置 Apache

什么是 Apache?

Apache(Apache HTTP Server) 是一款开源的 Web 服务器,以其稳定性、可扩展性和强大的安全特性著称。全球约有 30% 的服务器使用 Apache

主要特性:

  • 免费且开源
  • 模块化架构,便于扩展
  • SSL/TLS 支持,用于 HTTPS 配置
  • 虚拟主机,可托管多个网站

安装 Apache

在 Ubuntu 上,使用 apt 包管理器即可轻松安装 Apache。

安装 Apache

运行以下命令安装 Apache:

sudo apt update
sudo apt install apache2 -y

验证安装

安装完成后,检查 Apache 版本:

apache2 -v

示例输出:

Server version: Apache/2.4.52 (Ubuntu)
Server built:   2023-07-01T12:34:56

如果出现版本信息,则说明 Apache 已正确安装。

启动、停止与重启 Apache

Apache 通过 systemctl 命令进行管理。

启动 Apache

sudo systemctl start apache2

Apache 现在将开始接受 Web 请求。

启用自动启动

%%CODEBLOCK7%%

系统启动时,Apache 将自动启动。

sudo systemctl enable apache2

检查 Apache 状态

使用此命令验证 Apache 是否正在运行:

sudo systemctl status apache2

示例输出:

● apache2.service - The Apache HTTP Server
   Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor preset: enabled)
   Active: active (running) since ...

重启或停止 Apache

修改配置设置后重启 Apache:

sudo systemctl restart apache2

临时停止 Apache:

sudo systemctl stop apache2

验证 Apache 操作

要确认 Apache 正常运行,请访问服务器的 IP 地址

1. 检查服务器的 IP 地址

hostname -I

或检查外部 IP:

curl ifconfig.me

2. 在 Web 浏览器中验证

在浏览器中输入以下内容:

http://<your-server-ip>/

对于本地设置:

http://localhost/

您应该看到 Apache 的默认页面(/var/www/html/index.html)。

示例默认页面:

Apache2 Ubuntu Default Page
It works!

如果出现此消息,则 Apache 正常运行。

配置防火墙

Ubuntu 使用 UFW (Uncomplicated Firewall) 来管理防火墙规则。
安装 Apache 后,外部访问 HTTP (端口 80) 和 HTTPS (端口 443) 可能仍被阻止。

允许 Apache 通过防火墙

sudo ufw allow 'Apache'

同样允许 HTTPS:

sudo ufw allow 'Apache Full'

检查防火墙状态

sudo ufw status

示例输出:

Status: active

To                         Action      From
--                         ------      ----
Apache                     ALLOW       Anywhere
Apache (v6)                ALLOW       Anywhere (v6)

如果出现此内容,则 Apache 流量已允许通过防火墙。

总结

到目前为止,您已在 Ubuntu 上安装 Apache 并完成基本设置步骤
涵盖的关键点:

  • 如何安装 Apache
  • 如何启动和启用 Apache
  • 如何在浏览器中验证 Apache 操作
  • 如何配置 UFW 防火墙规则
  • Apache 基本配置文件概述

4. 配置虚拟主机(管理多个站点)

什么是虚拟主机?

虚拟主机允许您在单个 Apache 服务器上托管多个域(或子域)
例如,一个服务器可以同时托管 example.comtest.com

虚拟主机有两种类型:

  1. 基于名称的虚拟主机
  • 多个站点共享相同的 IP 地址
  • 最常见的方法
  1. 基于 IP 的虚拟主机
  • 每个站点使用不同的 IP 地址
  • 需要服务器上的多个网络接口

在大多数情况下,使用基于名称的虚拟主机

配置虚拟主机的步骤

1. 创建所需目录

为每个网站创建一个单独的目录

sudo mkdir -p /var/www/example.com/public_html
sudo mkdir -p /var/www/test.com/public_html

2. 更改目录所有权

通过将所有者设置为 www-data 确保 Apache 可以读取文件:

sudo chown -R www-data:www-data /var/www/example.com/public_html
sudo chown -R www-data:www-data /var/www/test.com/public_html

3. 创建占位符 HTML 文件

为测试创建一个基本的 index.html 文件:

echo "<h1>Welcome to example.com</h1>" | sudo tee /var/www/example.com/public_html/index.html
echo "<h1>Welcome to test.com</h1>" | sudo tee /var/www/test.com/public_html/index.html

4. 创建虚拟主机配置文件

虚拟主机配置文件存储在 /etc/apache2/sites-available/ 目录中。

example.com 的虚拟主机配置

使用以下命令创建并编辑配置文件:

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

配置文件内容:

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

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

    ErrorLog ${APACHE_LOG_DIR}/example.com_error.log
    CustomLog ${APACHE_LOG_DIR}/example.com_access.log combined
</VirtualHost>

test.com 的虚拟主机配置

sudo nano /etc/apache2/sites-available/test.com.conf

添加以下内容:

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

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

    ErrorLog ${APACHE_LOG_DIR}/test.com_error.log
    CustomLog ${APACHE_LOG_DIR}/test.com_access.log combined
</VirtualHost>

5. 启用虚拟主机

创建配置文件后,使用 a2ensite 启用虚拟主机:

sudo a2ensite example.com.conf
sudo a2ensite test.com.conf

测试 Apache 配置

检查语法错误:

sudo apachectl configtest

示例输出:

Syntax OK

如果没有错误,重启 Apache:

sudo systemctl restart apache2

6. 本地验证(编辑 hosts 文件)

要在本地测试虚拟主机,请编辑电脑的 hosts 文件。

sudo nano /etc/hosts

添加以下行:

127.0.0.1 example.com
127.0.0.1 test.com

保存文件后,打开浏览器访问:

http://example.com/

你应该看到 “Welcome to example.com”

同样,访问:

http://test.com/

应显示 “Welcome to test.com”

7. 虚拟主机故障排除

如果虚拟主机未正常工作,请检查以下内容:

1. 检查 Apache 错误日志

sudo tail -f /var/log/apache2/error.log

2. 确认配置文件已启用

ls /etc/apache2/sites-enabled/

如果列出了正确的 .conf 文件,则虚拟主机已激活。

3. 检查 Apache 端口设置

确认已配置端口 80(HTTP):

sudo nano /etc/apache2/ports.conf

确保存在以下行:

Listen 80

小结

本节说明了 如何在 Ubuntu 上配置 Apache 虚拟主机
关键要点:

  • 虚拟主机的概念和目的
  • 为每个站点创建目录
  • 创建并启用虚拟主机配置文件
  • 使用 hosts 文件进行本地测试的方法
  • 常见问题的故障排除

5. 介绍 SSL/TLS(启用 HTTPS)

什么是 SSL/TLS?

SSL(安全套接字层)和 TLS(传输层安全)是用于确保互联网安全通信的加密技术。

启用 SSL/TLS 的好处

加密通信(降低数据被拦截或篡改的风险)
提升 Google SEO 排名(HTTPS 站点优先)
防止浏览器安全警告(HTTP 站点会显示“Not Secure”)
保护登录凭据和在线交易

目前,推荐使用 TLS(TLS 1.2 / 1.3),而较旧的 SSL 版本(SSL 3.0 及更早)已被弃用。

使用 Let’s Encrypt 获取免费 SSL 证书

Let’s Encrypt 是提供免费 SSL 证书的证书颁发机构(CA)。
使用 certbot,您可以轻松颁发证书并在 Apache 中进行配置。

安装 Let’s Encrypt 客户端(Certbot)

安装 certbot,官方的 Let’s Encrypt 客户端:

sudo apt update
sudo apt install certbot python3-certbot-apache -y

自动化 Apache SSL 配置

您可以使用以下命令自动配置 Apache:

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

此命令执行以下操作:

  1. 域验证(HTTP-01 挑战)
  2. SSL 证书签发
  3. 自动 Apache SSL 配置
  4. 可选的 HTTP 到 HTTPS 重定向

验证 SSL 操作

访问以下 URL 以确认已启用 HTTPS:

https://example.com/

如果浏览器显示 锁形图标,则 SSL 已成功应用。

手动为 Apache 配置 SSL

如果您不想使用 certbot --apache,可以手动配置 SSL。

1. 启用 Apache 的 SSL 模块

sudo a2enmod ssl
sudo systemctl restart apache2

2. 配置 SSL 虚拟主机

编辑 SSL 配置文件 /etc/apache2/sites-available/example.com-le-ssl.conf

sudo nano /etc/apache2/sites-available/example.com-le-ssl.conf

配置示例:

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

    SSLEngine on
    SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem

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

    ErrorLog ${APACHE_LOG_DIR}/example.com_error.log
    CustomLog ${APACHE_LOG_DIR}/example.com_access.log combined
</VirtualHost>

3. 启用 SSL 配置并重启 Apache

sudo a2ensite example.com-le-ssl.conf
sudo systemctl restart apache2

SSL 证书的自动续订

Let’s Encrypt 证书有效期为 90 天。为避免手动续订,请配置自动更新。

1. 测试 Certbot 自动续订

sudo certbot renew --dry-run

2. 检查续订计划

Certbot 的自动续订计划存储在 /etc/cron.d/certbot 中。

sudo systemctl list-timers | grep certbot

SSL 故障排除

1. SSL 证书未生效

解决方案:重启 Apache 并验证配置

sudo systemctl restart apache2
sudo apachectl configtest

2. 证书已过期

sudo certbot renew --force-renewal

3. Let’s Encrypt 验证错误

解决方案:检查防火墙规则

sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw reload

总结

本节说明了如何 使用 Let’s Encrypt 安装和配置免费 SSL
关键要点:

  • SSL/TLS 基础
  • 使用 Let’s Encrypt 配置 Apache
  • 手动 SSL 配置
  • 自动证书续订
  • SSL 问题排查

6. 加强 Web 服务器安全

配置防火墙 (UFW)

Ubuntu 使用 UFW(简易防火墙) 来阻止不必要的流量并保护服务器。

检查当前防火墙设置

sudo ufw status

仅允许必要的端口

默认情况下,阻止所有入站流量,仅允许必要的端口:

sudo ufw default deny incoming
sudo ufw default allow outgoing

打开必要的端口:

  • SSH(端口 22)
    sudo ufw allow 22/tcp
    
  • HTTP(端口 80)
    sudo ufw allow 80/tcp
    
  • HTTPS(端口 443)
    sudo ufw allow 443/tcp
    

启用防火墙

sudo ufw enable

加强 SSH 安全

如果保持默认设置,SSH 是暴力攻击的常见目标。通过适当的配置来加强安全。

更改 SSH 端口

sudo nano /etc/ssh/sshd_config

修改以下行:

Port 2222  # Change from 22 to any unused port
PermitRootLogin no  # Disable root login
PasswordAuthentication no  # Disable password login (use SSH keys only)

重启 SSH:

sudo systemctl restart ssh

安装 Fail2Ban

Fail2Ban 通过临时禁止尝试重复 SSH 登录失败的 IP 地址来保护您的服务器。

sudo apt install fail2ban -y

编辑配置:

sudo nano /etc/fail2ban/jail.local

添加以下内容:

[sshd]
enabled = true
port = 2222
maxretry = 3
bantime = 600

启用 Fail2Ban:

sudo systemctl restart fail2ban
sudo systemctl enable fail2ban

强化 Apache 安全性

隐藏 Apache 版本信息

sudo nano /etc/apache2/conf-available/security.conf

更改以下设置:

ServerTokens Prod
ServerSignature Off

应用更改:

sudo systemctl restart apache2

禁用目录列表

sudo nano /etc/apache2/apache2.conf

定位目录块并更新:

<Directory /var/www/>
    Options -Indexes +FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

重启 Apache:

sudo systemctl restart apache2

禁用不必要的 Apache 模块

sudo a2dismod autoindex
sudo a2dismod status
sudo systemctl restart apache2

添加安全标头

安全标头保护您的网站免受跨站脚本和点击劫持等攻击。

启用 mod_headers

sudo a2enmod headers
sudo systemctl restart apache2

添加安全标头

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

<VirtualHost> 块内添加以下内容:

<IfModule mod_headers.c>
    Header always set X-Content-Type-Options "nosniff"
    Header always set X-XSS-Protection "1; mode=block"
    Header always set X-Frame-Options "SAMEORIGIN"
    Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"
</IfModule>

重启 Apache:

sudo systemctl restart apache2

故障排除

检查防火墙设置

sudo ufw status

检查 Apache 配置错误

sudo apachectl configtest

输出示例:

Syntax OK

更改端口后无法通过 SSH 连接

如果更改端口后 SSH 无法连接,请在连接时指定新端口:

ssh -p 2222 user@server-ip

总结

本节解释了如何加强 Web 服务器的安全性
关键要点:

  • 配置 UFW 防火墙规则
  • 保护 SSH(端口更改、Fail2Ban)
  • Apache 安全性强化(隐藏版本信息、禁用列表)
  • 添加安全标头

7. 性能优化

调整 Apache

默认 Apache 配置可能无法提供最佳性能。通过应用以下调整,您可以实现显著更高的性能

优化 MPM(多处理模块)

MPM(多处理模块)决定了 Apache 如何处理请求。

检查当前 MPM:

apachectl -M | grep mpm

示例输出:

mpm_prefork_module (shared)

如果启用了 mpm_prefork_module,切换到 mpm_event 可以提高性能。

更改 MPM:

sudo a2dismod mpm_prefork
sudo a2enmod mpm_event
sudo systemctl restart apache2

启用 KeepAlive

KeepAlive(持久连接)允许客户端重用现有连接,减少请求开销。

编辑配置文件:

sudo nano /etc/apache2/apache2.conf

确认以下设置:

KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5

重启 Apache:

sudo systemctl restart apache2

使用缓存

通过利用浏览器缓存和服务器端缓存,您可以减少不必要的请求并显著提高响应速度

启用 mod_expires(浏览器缓存)

sudo a2enmod expires
sudo systemctl restart apache2

将以下内容添加到 /etc/apache2/sites-available/example.com.conf

<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresDefault "access plus 1 month"
    ExpiresByType image/jpg "access plus 1 year"
    ExpiresByType image/jpeg "access plus 1 year"
    ExpiresByType image/png "access plus 1 year"
    ExpiresByType text/css "access plus 1 month"
    ExpiresByType application/javascript "access plus 1 month"
</IfModule>

重启 Apache:

sudo systemctl restart apache2

启用 mod_cache (服务器缓存)

sudo a2enmod cache cache_disk
sudo systemctl restart apache2

将以下内容添加到 /etc/apache2/sites-available/example.com.conf

<IfModule mod_cache.c>
    CacheEnable disk /
    CacheRoot /var/cache/apache2/mod_cache_disk
    CacheDefaultExpire 86400
</IfModule>

重启 Apache:

sudo systemctl restart apache2

启用压缩

使用 mod_deflate 压缩网站数据并减少传输大小。

启用 mod_deflate

sudo a2enmod deflate
sudo systemctl restart apache2

将以下内容添加到 /etc/apache2/sites-available/example.com.conf

<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/plain text/xml
    AddOutputFilterByType DEFLATE text/css
    AddOutputFilterByType DEFLATE application/javascript
    AddOutputFilterByType DEFLATE image/svg+xml
</IfModule>

重启 Apache:

sudo systemctl restart apache2

资源限制

为了准备应对高流量或潜在的恶意访问,使用 Apache 模块设置资源限制

启用 mod_ratelimit

sudo a2enmod ratelimit
sudo systemctl restart apache2

将以下内容添加到 /etc/apache2/sites-available/example.com.conf

<Location />
    SetOutputFilter RATE_LIMIT
    SetEnv rate-limit 200
</Location>

重启 Apache:

sudo systemctl restart apache2

故障排除性能问题

检查 Apache 错误日志

sudo tail -f /var/log/apache2/error.log

检查 Apache 负载状态

sudo apachectl status

检查 CPU 和内存使用情况

top

htop

如果未安装 htop

sudo apt install htop

总结

本节解释了如何优化 Web 服务器性能
关键要点:

  • 调整 Apache (MPM 优化和 KeepAlive 设置)
  • 使用缓存 (浏览器缓存和服务器缓存)
  • 使用 mod_deflate 进行数据压缩
  • 使用 mod_ratelimit 进行资源控制

8. 故障排除

Apache 无法启动

如果 Apache 无法启动,配置错误是最常见的原因。

1. 检查错误消息

sudo systemctl status apache2

2. 测试配置

sudo apachectl configtest

如果输出包含 “Syntax error”,请验证错误消息中列出的路径或设置。

3. 重启 Apache

sudo systemctl restart apache2

无法访问服务器

如果在浏览器中无法访问服务器,请验证以下项目。

1. 检查防火墙设置

sudo ufw status

确保允许端口 80443

2. 检查 Apache 状态

sudo systemctl status apache2

3. 检查服务器 IP 地址

hostname -I

虚拟主机不工作

如果虚拟主机未按预期行为,请重新检查配置。

1. 确认虚拟主机文件已启用

ls /etc/apache2/sites-enabled/

如果您的 .conf 未列出,请启用它:

sudo a2ensite example.com.conf
sudo systemctl restart apache2

2. 检查主机名解析

如果在本地测试,请确保 /etc/hosts 文件包含:

127.0.0.1 example.com

3. 检查 DocumentRoot 路径

不正确的路径通常会导致虚拟主机问题。

DocumentRoot /var/www/example.com/public_html

SSL 证书问题

1. HTTPS 不工作

确认 SSL 已启用:

sudo apachectl -M | grep ssl

如有必要,请启用:

sudo a2enmod ssl
sudo systemctl restart apache2

2. 证书已过期

sudo certbot renew

3. Let’s Encrypt 验证失败

HTTP 验证需要打开 80 端口。

sudo ufw allow 80/tcp
sudo systemctl restart apache2

网站性能缓慢

1. 检查服务器负载

top

2. 查看 Apache 日志

sudo tail -f /var/log/apache2/access.log

3. 确认缓存设置

确保已启用 mod_expiresmod_cachemod_deflate

权限错误(403 Forbidden)

此错误通常表示文件或目录权限不正确。

1. 检查目录所有者

sudo chown -R www-data:www-data /var/www/example.com

2. 检查目录权限

sudo chmod -R 755 /var/www/example.com

错误日志监控

在故障排除期间始终监控错误日志:

sudo tail -f /var/log/apache2/error.log

摘要

本节提供了针对 Ubuntu Web 服务器的常见问题排查方法。关键要点:

  • Apache 启动错误和配置检查
  • 防火墙和网络相关问题
  • 虚拟主机配置问题
  • SSL 证书错误和续订
  • 性能和权限排查

9. 摘要

在本文中,我们解释了如何使用 Apache 在 Ubuntu 上构建完整的 Web 服务器环境,并包括安全增强、性能优化和故障排除技术。

按照本指南操作,您可以运行一个稳定、安全且高性能的 Web 服务器,适用于个人项目和企业级应用。

✔ 本指南涵盖的关键要点

  • 安装 Ubuntu 并进行初始系统配置
  • 安装和配置 Apache
  • 设置虚拟主机 以管理多个网站
  • 使用 Let’s Encrypt 免费 SSL 证书启用 HTTPS
  • 增强服务器安全(UFW、SSH 加固、Apache 设置)
  • 提升性能(缓存、压缩、MPM 调优)
  • 排查服务器运行中的常见问题

✔ 完成本指南后您可以实现的目标

  • 在单台 Ubuntu 服务器上托管多个网站
  • 使用现代 SSL/TLS 确保安全通信
  • 通过缓存和压缩提升站点速度和可靠性
  • 使用 Apache 日志和系统工具快速诊断并解决问题

✔ 推荐的后续步骤

  • 安装 PHP 和 MySQL/MariaDB,构建完整的 LAMP 环境
  • 部署 WordPress 或其他 CMS
  • 实现自动备份方案
  • 考虑使用云服务(AWS、GCP、Azure 等)

通过适当的配置和维护,Ubuntu Web 服务器可以提供长期的稳定性和卓越的性能。我们希望本指南能帮助您构建可靠且安全的服务器环境。

年収訴求