以下是 Apache HTTP Server 在主流 Linux 系统上的详细安装教程,涵盖基础安装、配置及常见问题排查:
一、安装前准备
1. 更新系统包
bash复制代码
# Debian/Ubuntu
sudo apt update && sudo apt upgrade -y
# CentOS/RHEL
sudo yum update -y # CentOS 7 及以下
sudo dnf update -y # CentOS 8+/RHEL 8+
二、安装 Apache
Debian/Ubuntu
bash复制代码sudo apt install apache2 -y
CentOS/RHEL
bash复制代码
# CentOS 7 及以下
sudo yum install httpd -y
# CentOS 8+/RHEL 8+
sudo dnf install httpd -y
三、启动 Apache 服务
1. 启动服务
bash复制代码
# Debian/Ubuntu
sudo systemctl start apache2
# CentOS/RHEL
sudo systemctl start httpd
2. 设置开机自启
bash复制代码
# Debian/Ubuntu
sudo systemctl enable apache2
# CentOS/RHEL
sudo systemctl enable httpd
3. 检查服务状态
bash复制代码
# Debian/Ubuntu
sudo systemctl status apache2
# CentOS/RHEL
sudo systemctl status httpd
四、配置防火墙
1. 开放 HTTP/HTTPS 端口
bash复制代码
# Debian/Ubuntu (UFW)
sudo ufw allow 80/tcp # HTTP
sudo ufw allow 443/tcp # HTTPS(可选)
sudo ufw reload
# CentOS/RHEL (firewalld)
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https # 可选
sudo firewall-cmd --reload
2. 验证端口监听
bash复制代码sudo netstat -tuln | grep ':80'
五、测试访问
打开浏览器,访问:
复制代码http://服务器IP 或 http://localhost
若看到 "Apache2 Ubuntu Default Page" 或 "Test Page for Apache HTTP Server",则安装成功。
六、基础配置示例
1. 修改默认端口(如改为 8080)
bash复制代码
# 编辑配置文件
sudo nano /etc/apache2/ports.conf # Debian/Ubuntu
sudo nano /etc/httpd/conf/httpd.conf # CentOS/RHEL
# 找到 "Listen 80" 并修改为:
Listen 8080
# 重启服务
sudo systemctl restart apache2 # Debian/Ubuntu
sudo systemctl restart httpd # CentOS/RHEL
2. 配置虚拟主机(托管多个网站)
创建配置文件:
bash复制代码sudo nano /etc/apache2/sites-available/example.com.conf # Debian/Ubuntusudo nano /etc/httpd/conf.d/example.com.conf # CentOS/RHEL
添加内容(示例):
apache复制代码
<VirtualHost *:80>
ServerAdmin admin@example.com
ServerName example.com
ServerAlias www.example.com
DocumentRoot /var/www/example.com/public_html
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
启用配置并重启:
bash复制代码
# Debian/Ubuntu
sudo a2ensite example.com.conf
sudo systemctl reload apache2
# CentOS/RHEL
sudo systemctl restart httpd
七、常见问题排查
1. 无法访问页面
检查防火墙:确保端口开放。
查看日志:
bash复制代码
# Debian/Ubuntu
tail -f /var/log/apache2/error.log
# CentOS/RHEL
tail -f /var/log/httpd/error_log
SELinux 问题(CentOS/RHEL):
bash复制代码
# 临时禁用 SELinux
sudo setenforce 0
# 永久禁用(编辑 /etc/selinux/config)
sudo sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
2. 权限问题
确保网站目录权限正确:
bash复制代码sudo chown -R www-data:www-data /var/www/example.com # Debian/Ubuntusudo chown -R apache:apache /var/www/example.com # CentOS/RHELsudo chmod -R 755 /var/www/example.com
八、卸载 Apache
bash复制代码
# Debian/Ubuntu
sudo apt purge apache2 -y
sudo apt autoremove -y
# CentOS/RHEL
sudo yum remove httpd -y # CentOS 7 及以下
sudo dnf remove httpd -y # CentOS 8+/RHEL 8+
通过以上步骤,您已完成 Apache 的基础安装与配置。如需进一步学习高级功能(如 HTTPS、负载均衡、模块开发等),可参考 https://httpd.apache.org/docs/。