在 CentOS 上安装和配置 Web 服务器(以最常用的 Apache 和 Nginx 为例)的步骤如下:
Apache 是最流行的 Web 服务器之一,适合大多数场景。
sudo yum update -y
sudo yum install httpd -y
sudo systemctl start httpd
sudo systemctl enable httpd
sudo systemctl status httpd
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload
在浏览器中访问服务器的 IP 地址(如 http://你的服务器IP),若看到 "Apache 测试页面" 则表示安装成功。
- 默认网站根目录:
/var/www/html/(可将网页文件放在这里)
- 配置文件目录:
/etc/httpd/conf.d/(新增网站配置需在此目录创建 .conf 文件)
示例:创建一个自定义页面
echo "<h1>Hello, CentOS Apache!</h1>" | sudo tee /var/www/html/index.html
Nginx 以轻量、高性能著称,适合高并发场景。
CentOS 默认源包含 Nginx,直接安装:
sudo yum update -y
sudo yum install nginx -y
sudo systemctl start nginx
sudo systemctl enable nginx
sudo systemctl status nginx
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload
访问服务器 IP(http://你的服务器IP),看到 "Welcome to nginx!" 页面即成功。
- 默认网站根目录:
/usr/share/nginx/html/
- 配置文件目录:
/etc/nginx/conf.d/(新增网站需创建 .conf 文件)
示例:创建自定义页面
echo "<h1>Hello, CentOS Nginx!</h1>" | sudo tee /usr/share/nginx/html/index.html
若需托管多个网站,可配置虚拟主机(基于域名区分)。
- 创建网站目录和测试文件:
sudo mkdir -p /var/www/example.com/html
sudo echo "<h1>Example.com 网站</h1>" | sudo tee /var/www/example.com/html/index.html
sudo chown -R $USER:$USER /var/www/example.com/html
- 创建配置文件:
sudo vi /etc/httpd/conf.d/example.com.conf
添加以下内容(替换 example.com 为你的域名):
<VirtualHost *:80>
ServerName example.com
ServerAlias www.example.com
DocumentRoot /var/www/example.com/html
ErrorLog /var/log/httpd/example.com.error.log
CustomLog /var/log/httpd/example.com.access.log combined
</VirtualHost>
- 重启 Apache 生效:
sudo systemctl restart httpd
- 创建网站目录和测试文件:
sudo mkdir -p /usr/share/nginx/example.com/html
sudo echo "<h1>Example.com 网站</h1>" | sudo tee /usr/share/nginx/example.com/html/index.html
sudo chown -R $USER:$USER /usr/share/nginx/example.com/html
- 创建配置文件:
sudo vi /etc/nginx/conf.d/example.com.conf
添加以下内容:
server {
listen 80;
server_name example.com www.example.com;
root /usr/share/nginx/example.com/html;
index index.html;
access_log /var/log/nginx/example.com.access.log;
error_log /var/log/nginx/example.com.error.log;
}
- 检查配置并重启 Nginx:
sudo nginx -t
sudo systemctl restart nginx
通过 Let's Encrypt 免费证书启用 HTTPS:
- 安装 Certbot:
sudo yum install certbot python3-certbot-apache -y
sudo yum install certbot python3-certbot-nginx -y
- 自动配置证书(替换为你的域名):
sudo certbot --apache -d example.com -d www.example.com
sudo certbot --nginx -d example.com -d www.example.com
证书会自动续期,无需手动操作。
- 选择 Apache 还是 Nginx:Apache 配置简单、模块丰富;Nginx 性能更好,适合高并发。
- 核心步骤:安装服务 → 启动并配置自启 → 开放防火墙 → 配置网站(虚拟主机)→ 可选 HTTPS 加密。
根据需求选择合适的服务器,配置完成后即可通过域名或 IP 访问你的网站。