在CentOS 7.8上配置基础的Web服务器环境,通常包括安装Apache/Nginx、PHP和MySQL/MariaDB。以下是基于LAMP(Linux + Apache + MariaDB + PHP)的配置步骤:
1. 系统更新与准备
# 更新系统
sudo yum update -y
# 安装常用工具
sudo yum install -y wget vim net-tools epel-release
2. 安装Apache(httpd)
# 安装Apache
sudo yum install -y httpd
# 启动并设置开机自启
sudo systemctl start httpd
sudo systemctl enable httpd
# 检查状态
sudo systemctl status httpd
# 防火墙放行HTTP/HTTPS(如果防火墙开启)
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload
验证:浏览器访问 http://服务器IP,应看到Apache测试页。
3. 安装MariaDB(MySQL替代)
# 安装MariaDB
sudo yum install -y mariadb-server mariadb
# 启动并设置开机自启
sudo systemctl start mariadb
sudo systemctl enable mariadb
# 运行安全初始化脚本
sudo mysql_secure_installation
按提示设置root密码、移除匿名用户、禁止远程root登录等。
4. 安装PHP及常用扩展
# 安装PHP 7.4(需启用Remi仓库)
sudo yum install -y https://rpms.remirepo.net/enterprise/remi-release-7.rpm
sudo yum-config-manager --enable remi-php74
sudo yum install -y php php-cli php-fpm php-mysqlnd php-json php-gd php-mbstring php-xml
# 验证PHP版本
php -v
# 重启Apache使PHP生效
sudo systemctl restart httpd
测试PHP:创建测试文件 /var/www/html/info.php,内容为 <?php phpinfo(); ?>,访问 http://服务器IP/info.php。
5. 配置目录权限(可选)
# 设置Web目录权限
sudo chown -R apache:apache /var/www/html
sudo chmod -R 755 /var/www/html
6. 其他可选组件
-
安装phpMyAdmin(管理数据库):
sudo yum install -y phpmyadmin # 配置文件:/etc/httpd/conf.d/phpMyAdmin.conf # 建议限制访问IP或通过HTTPS使用 -
配置虚拟主机:
编辑/etc/httpd/conf/httpd.conf或创建/etc/httpd/conf.d/your-site.conf。 -
启用HTTPS(使用Let’s Encrypt):
安装Certbot并配置SSL证书。
7. 常用命令汇总
# 服务管理
sudo systemctl restart httpd # 重启Apache
sudo systemctl status mariadb # 查看MariaDB状态
# 日志查看
sudo tail -f /var/log/httpd/access_log
sudo tail -f /var/log/httpd/error_log
注意事项
- SELinux:如遇权限问题,可临时禁用(
setenforce 0)或调整策略。 - 防火墙:确保开放80/443端口,或关闭防火墙(仅测试环境):
sudo systemctl stop firewalld sudo systemctl disable firewalld - 安全建议:
- 修改默认的Apache欢迎页。
- 定期更新系统及软件。
- 为MySQL/MariaDB设置强密码。
- 删除测试文件(如
info.php)。
如果需要配置 Nginx + PHP-FPM 或 LEMP 环境,步骤会有所不同。请根据实际需求选择Web服务器!
CLOUD技术笔记