奋斗
努力

怎么在 CentOS 7.6 建设网站?

云计算

在 CentOS 7.6 上建设网站需要经过多个步骤,包括环境配置、Web服务器安装、数据库设置等。以下是详细指南:


1. 准备工作

  • 更新系统
    确保系统是最新状态:

    sudo yum update -y
    sudo reboot  # 可选,重大更新后建议重启

2. 安装 Web 服务器

选项1:Apache

sudo yum install httpd -y
sudo systemctl start httpd
sudo systemctl enable httpd
  • 验证:浏览器访问 http://服务器IP,应看到 Apache 测试页。
  • 防火墙放行 HTTP/HTTPS
    sudo firewall-cmd --permanent --add-service=http
    sudo firewall-cmd --permanent --add-service=https
    sudo firewall-cmd --reload

选项2:Nginx

sudo yum install epel-release -y
sudo yum install nginx -y
sudo systemctl start nginx
sudo systemctl enable nginx
  • 验证:访问 http://服务器IP,看到 Nginx 欢迎页。
  • 防火墙配置(同上)。

3. 安装数据库

MySQL/MariaDB

sudo yum install mariadb-server mariadb -y
sudo systemctl start mariadb
sudo systemctl enable mariadb
  • 安全初始化
    sudo mysql_secure_installation

    按提示设置 root 密码并移除测试数据库。

PostgreSQL(可选)

sudo yum install postgresql-server postgresql-contrib -y
sudo postgresql-setup initdb
sudo systemctl start postgresql
sudo systemctl enable postgresql

4. 安装 PHP(如需动态网站)

sudo yum install php php-mysql php-fpm -y  # 基础包
sudo yum install php-gd php-json php-mbstring php-xml php-zip  # 常用扩展
  • 重启 Apache/Nginx
    • Apache: sudo systemctl restart httpd
    • Nginx: 需配置 PHP-FPM,编辑 /etc/nginx/conf.d/default.conf 添加 FastCGI 支持。

5. 部署网站文件

  • 默认目录
    • Apache: /var/www/html/
    • Nginx: /usr/share/nginx/html/
  • 上传文件
    • 使用 scp 或 FTP 工具上传代码:
      scp -r local_folder user@server_ip:/var/www/html/
    • 确保权限正确:
      sudo chown -R apache:apache /var/www/html/  # Apache
      sudo chown -R nginx:nginx /usr/share/nginx/html/  # Nginx

6. 配置虚拟主机(多站点可选)

Apache

  1. 创建配置文件 /etc/httpd/conf.d/yourdomain.conf
    <VirtualHost *:80>
       ServerName yourdomain.com
       DocumentRoot /var/www/yourdomain
       ErrorLog /var/log/httpd/yourdomain-error.log
       CustomLog /var/log/httpd/yourdomain-access.log combined
    </VirtualHost>
  2. 重启 Apache:
    sudo systemctl restart httpd

Nginx

  1. 创建配置文件 /etc/nginx/conf.d/yourdomain.conf
    server {
       listen 80;
       server_name yourdomain.com;
       root /usr/share/nginx/yourdomain;
       index index.html index.php;
    }
  2. 重启 Nginx:
    sudo systemctl restart nginx

7. 域名与 DNS 配置

  • 域名解析:在域名注册商处将域名 A 记录指向服务器 IP。
  • 本地测试:修改本地 hosts 文件临时测试:
    服务器IP yourdomain.com

8. 启用 HTTPS(SSL 证书)

使用 Let’s Encrypt 免费证书:

sudo yum install certbot python2-certbot-nginx -y  # Nginx
sudo certbot --nginx -d yourdomain.com

证书会自动续期。Apache 用户替换为 python2-certbot-apache


9. 测试与维护

  • 检查服务状态
    sudo systemctl status httpd/nginx/mariadb
  • 日志排查
    • Apache: /var/log/httpd/error_log
    • Nginx: /var/log/nginx/error.log

常见问题

  • 403 Forbidden:检查文件权限或 SELinux 状态(临时禁用:sudo setenforce 0)。
  • 数据库连接失败:确保用户权限及防火墙规则。

通过以上步骤,您可以在 CentOS 7.6 上成功搭建一个支持动态内容的网站。如需更复杂的应用(如 WordPress),可进一步安装对应的 CMS 系统。

未经允许不得转载:云服务器 » 怎么在 CentOS 7.6 建设网站?