在 CentOS 8.2 64bit 系统上搭建一个网站,通常是指部署一个 Web 服务器(如 Apache 或 Nginx),并结合数据库(如 MySQL/MariaDB)和后端语言(如 PHP、Python、Node.js)来运行你的网站内容。下面是一个通用的建站流程,以搭建 LAMP(Linux + Apache + MariaDB + PHP)为例:
🧱 一、准备环境
确保你已经安装了 CentOS 8.2 64bit,并具有 root 权限或 sudo 权限。
📦 二、安装 Apache(Web 服务器)
sudo dnf install httpd -y
启动 Apache 并设置开机自启:
sudo systemctl start httpd
sudo systemctl enable httpd
检查状态:
sudo systemctl status httpd
开放防火墙端口(80 HTTP / 443 HTTPS):
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload
测试访问:浏览器访问 http://你的服务器IP,看到 Apache 默认页面即成功。
💾 三、安装 MariaDB(MySQL 替代)
sudo dnf install mariadb-server mariadb -y
启动 MariaDB 并设置开机自启:
sudo systemctl start mariadb
sudo systemctl enable mariadb
运行安全初始化脚本(设置 root 密码等):
sudo mysql_secure_installation
登录 MariaDB 测试:
mysql -u root -p
🔐 四、安装 PHP 及相关模块
sudo dnf install php php-mysqlnd php-cli php-gd php-curl php-mbstring php-xml php-json -y
重启 Apache 使 PHP 生效:
sudo systemctl restart httpd
创建测试文件 /var/www/html/info.php:
sudo nano /var/www/html/info.php
写入以下内容:
<?php
phpinfo();
?>
保存后,在浏览器中访问 http://你的服务器IP/info.php,看到 PHP 配置信息页面说明 PHP 安装成功。
🗂️ 五、部署你的网站代码
你可以将网站文件放在 /var/www/html/ 目录下。
例如上传一个简单的 index.html:
echo "<h1>我的第一个网站</h1>" | sudo tee /var/www/html/index.html
然后通过浏览器访问即可。
如果你使用的是 WordPress、Discuz!、Typecho 等 CMS 程序,请上传对应的源码到这个目录,并配置数据库连接。
🔒 六、(可选)配置虚拟主机(Virtual Host)
如果你要托管多个网站,可以配置 Apache 的虚拟主机。
示例配置文件:
sudo nano /etc/httpd/conf.d/example.com.conf
写入类似如下内容:
<VirtualHost *:80>
ServerAdmin admin@example.com
DocumentRoot /var/www/example.com/public_html
ServerName example.com
ServerAlias www.example.com
<Directory /var/www/example.com/public_html>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
ErrorLog /var/log/httpd/example.com-error.log
CustomLog /var/log/httpd/example.com-access.log combined
</VirtualHost>
记得创建对应目录:
sudo mkdir -p /var/www/example.com/public_html
然后重启 Apache:
sudo systemctl restart httpd
🔒 七、(可选)安装 SSL 证书(HTTPS)
推荐使用 Let’s Encrypt 免费证书:
安装 EPEL 源:
sudo dnf install epel-release -y
安装 Certbot 和 Apache 插件:
sudo dnf install certbot python3-certbot-apache -y
申请证书(假设你已配置好域名解析):
sudo certbot --apache -d yourdomain.com -d www.yourdomain.com
按提示操作即可自动配置 HTTPS。
✅ 常见问题排查
| 问题 | 解决方法 |
|---|---|
| 网页无法访问 | 检查防火墙是否放行 80/443,检查 Apache 是否运行 |
| 数据库连接失败 | 检查用户名、密码、数据库是否存在 |
| PHP 不生效 | 检查 Apache 是否加载 PHP 模块,重启 Apache |
| 文件权限错误 | 设置 /var/www/html 下文件为 apache 用户组 |
📌 总结
你现在已经在 CentOS 8.2 上完成了以下基础建站步骤:
✅ 安装 Apache
✅ 安装 MariaDB
✅ 安装 PHP
✅ 配置防火墙
✅ 部署网站内容
✅ (可选)配置虚拟主机和 HTTPS
如果你有具体要部署的网站程序(比如 WordPress、Typecho、Django、Node.js 应用等),欢迎告诉我,我可以提供更详细的部署教程。
CLOUD技术博