首先安装apache服务,centos使用yum或dnf命令,ubuntu使用apt命令;接着启动并设置开机自启,通过systemctl命令管理服务状态;验证服务运行可通过浏览器访问IP或查看服务状态;然后配置虚拟主机,创建网站目录、设置权限、编写测试页面,并建立虚拟主机配置文件;最后调整防火墙规则,CentOS使用firewalld放行http/https,Ubuntu使用ufw允许Apache Full规则,完成配置后即可对外提供Web服务。
在linux系统中配置Apache服务是搭建Web服务器的基础操作。本文以常见的CentOS或Ubuntu系统为例,详细介绍如何安装、配置和管理Apache服务,确保你可以快速部署一个可用的网站。
安装Apache服务
不同Linux发行版使用不同的包管理工具来安装Apache(也称为httpd)。
CentOS / RHEL 系统:
sudo yum install httpd -y
或在较新版本中使用dnf:
sudo dnf install httpd -y
sudo apt update
sudo apt install apache2 -y
安装完成后,启动并设置开机自启:
CentOS:
sudo systemctl start httpd
sudo systemctl enable httpd
Ubuntu:
sudo systemctl start apache2
sudo systemctl enable apache2
验证Apache是否正常运行
启动服务后,可通过以下方式确认Apache已正常工作。
- 在浏览器中访问服务器IP地址,如:http://your_server_ip,应看到默认欢迎页面。
- 使用命令检查服务状态:
sudo systemctl status httpd # CentOS
sudo systemctl status apache2 # Ubuntu
如果显示“active (running)”,说明服务已启动成功。
配置虚拟主机(Virtual Host)
虚拟主机允许你在一台服务器上托管多个网站。以下是基于Ubuntu的配置示例,CentOS步骤类似。
1. 创建网站目录:
sudo mkdir -p /var/www/example.com/html
2. 设置权限:
sudo chown -R $USER:$USER /var/www/example.com/html
sudo chmod -R 755 /var/www/example.com
3. 创建测试页面:
nano /var/www/example.com/html/index.html
写入简单内容:
<html>
<head><title>Welcome to Example.com</title></head>
<body><h1>Hello from example.com!</h1></body>
</html>
4. 创建虚拟主机配置文件:
sudo nano /etc/apache2/sites-available/example.com.conf
添加如下内容:
<VirtualHost *:80>
ServerName example.com
ServerAlias www.example.com
DocumentRoot /var/www/example.com/html
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
5. 启用站点和重写模块:
sudo a2ensite example.com.conf
sudo a2enmod rewrite
sudo systemctl restart apache2
CentOS用户需手动编辑主配置文件或在/etc/httpd/conf.d/
下创建conf文件。
调整防火墙设置
若服务器启用防火墙,需放行HTTP(80)和HTTPS(443)端口。
CentOS(firewalld):
sudo firewall-cmd –permanent –add-service=http
sudo firewall-cmd –permanent –add-service=https
sudo firewall-cmd –reload
Ubuntu(ufw):
sudo ufw allow ‘Apache Full’
完成上述步骤后,你的Apache服务器即可对外提供Web服务。
基本上就这些。配置过程中注意路径、权限和语法正确性,避免因小错误导致服务无法启动。