引言

CentOS作为基于Red Hat Enterprise Linux(RHEL)的免费企业级操作系统,以其稳定性、安全性和长期支持而闻名,是搭建网站服务器的理想选择。本教程将手把手指导您完成从零开始在CentOS服务器上部署网站的完整过程,涵盖环境配置、站点部署、安全加固和性能优化等关键环节,并针对部署过程中可能遇到的常见问题提供解决方案。

1. 准备工作

1.1 服务器选择与系统安装

在开始之前,您需要一台服务器,可以是物理服务器、VPS或云服务器。推荐配置:

  • CPU: 至少2核心
  • 内存: 至少2GB(推荐4GB以上)
  • 硬盘: 至少20GB可用空间
  • 网络: 稳定的互联网连接

CentOS系统安装步骤:

  1. 下载CentOS镜像(推荐CentOS 7或CentOS 8 Stream)
  2. 创建启动盘并启动服务器
  3. 选择”Install CentOS 7”
  4. 设置语言、键盘布局
  5. 配置分区(推荐自动分区)
  6. 设置网络和主机名
  7. 设置root密码和创建普通用户
  8. 等待安装完成并重启

1.2 初始系统设置

系统安装完成后,进行基本设置:

# 更新系统 sudo yum update -y # 安装常用工具 sudo yum install -y wget curl vim git unzip # 设置时区 sudo timedatectl set-timezone Asia/Shanghai # 查看系统状态 sudo systemctl status 

1.3 基本安全设置

# 配置防火墙 sudo systemctl start firewalld sudo systemctl enable firewalld # 添加SSH服务到防火墙 sudo firewall-cmd --permanent --add-service=ssh sudo firewall-cmd --reload # 禁用root远程登录(可选,增强安全性) sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak sudo sed -i 's/#PermitRootLogin yes/PermitRootLogin no/' /etc/ssh/sshd_config sudo systemctl restart sshd # 创建新用户并设置sudo权限 sudo adduser deployer sudo passwd deployer sudo usermod -aG wheel deployer 

2. 环境配置

2.1 LAMP环境搭建

LAMP(Linux + Apache + MySQL + PHP)是最流行的网站环境组合之一。

2.1.1 安装Apache

# 安装Apache sudo yum install -y httpd # 启动Apache并设置开机自启 sudo systemctl start httpd sudo systemctl enable httpd # 检查Apache状态 sudo systemctl status httpd # 配置防火墙允许HTTP和HTTPS流量 sudo firewall-cmd --permanent --add-service=http sudo firewall-cmd --permanent --add-service=https sudo firewall-cmd --reload # 测试Apache是否正常工作 curl http://localhost 

2.1.2 安装MySQL/MariaDB

# 安装MariaDB(MySQL的分支) sudo yum install -y mariadb-server mariadb # 启动MariaDB并设置开机自启 sudo systemctl start mariadb sudo systemctl enable mariadb # 运行安全安装脚本 sudo mysql_secure_installation # 按照提示设置root密码、移除匿名用户、禁止root远程登录等 

2.1.3 安装PHP

# 安装EPEL仓库和Remi仓库(获取最新PHP版本) sudo yum install -y epel-release sudo yum install -y https://rpms.remirepo.net/enterprise/remi-release-7.rpm # 安装PHP及常用扩展 sudo yum-config-manager --enable remi-php74 sudo yum install -y php php-common php-opcache php-mysql php-gd php-xml php-mbstring php-json # 重启Apache使PHP生效 sudo systemctl restart httpd # 测试PHP是否正常工作 echo "<?php phpinfo(); ?>" | sudo tee /var/www/html/phpinfo.php curl http://localhost/phpinfo.php 

2.2 LNMP环境搭建

LNMP(Linux + Nginx + MySQL + PHP)是另一种流行的网站环境组合,以高并发性能著称。

2.2.1 安装Nginx

# 安装EPEL仓库 sudo yum install -y epel-release # 安装Nginx sudo yum install -y nginx # 启动Nginx并设置开机自启 sudo systemctl start nginx sudo systemctl enable nginx # 检查Nginx状态 sudo systemctl status nginx # 配置防火墙允许HTTP和HTTPS流量 sudo firewall-cmd --permanent --add-service=http sudo firewall-cmd --permanent --add-service=https sudo firewall-cmd --reload # 测试Nginx是否正常工作 curl http://localhost 

2.2.2 安装MySQL/MariaDB

与LAMP环境中的MySQL/MariaDB安装步骤相同,请参考2.1.2部分。

2.2.3 安装PHP-FPM

# 安装EPEL仓库和Remi仓库 sudo yum install -y epel-release sudo yum install -y https://rpms.remirepo.net/enterprise/remi-release-7.rpm # 安装PHP及常用扩展 sudo yum-config-manager --enable remi-php74 sudo yum install -y php php-common php-opcache php-mysql php-gd php-xml php-mbstring php-json php-fpm # 启动PHP-FPM并设置开机自启 sudo systemctl start php-fpm sudo systemctl enable php-fpm # 配置PHP-FPM sudo cp /etc/php-fpm.d/www.conf /etc/php-fpm.d/www.conf.bak sudo sed -i 's/user = apache/user = nginx/' /etc/php-fpm.d/www.conf sudo sed -i 's/group = apache/group = nginx/' /etc/php-fpm.d/www.conf sudo systemctl restart php-fpm # 配置Nginx使用PHP-FPM sudo cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak sudo tee /etc/nginx/conf.d/default.conf << EOF server { listen 80; server_name localhost; root /usr/share/nginx/html; index index.php index.html index.htm; location / { try_files $uri $uri/ /index.php?$query_string; } location ~ .php$ { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } } EOF # 重启Nginx使配置生效 sudo systemctl restart nginx # 测试PHP是否正常工作 echo "<?php phpinfo(); ?>" | sudo tee /usr/share/nginx/html/phpinfo.php curl http://localhost/phpinfo.php 

3. 网站部署

3.1 域名绑定与虚拟主机配置

3.1.1 Apache虚拟主机配置

# 创建网站目录 sudo mkdir -p /var/www/example.com sudo chown -R apache:apache /var/www/example.com sudo chmod -R 755 /var/www/example.com # 创建虚拟主机配置文件 sudo tee /etc/httpd/conf.d/example.com.conf << EOF <VirtualHost *:80> ServerName example.com ServerAlias www.example.com DocumentRoot /var/www/example.com ErrorLog /var/log/httpd/example.com-error.log CustomLog /var/log/httpd/example.com-access.log combined </VirtualHost> EOF # 重启Apache使配置生效 sudo systemctl restart httpd # 测试配置是否正确 sudo apachectl configtest 

3.1.2 Nginx虚拟主机配置

# 创建网站目录 sudo mkdir -p /usr/share/nginx/example.com sudo chown -R nginx:nginx /usr/share/nginx/example.com sudo chmod -R 755 /usr/share/nginx/example.com # 创建虚拟主机配置文件 sudo tee /etc/nginx/conf.d/example.com.conf << EOF server { listen 80; server_name example.com www.example.com; root /usr/share/nginx/example.com; index index.php index.html index.htm; access_log /var/log/nginx/example.com-access.log; error_log /var/log/nginx/example.com-error.log; location / { try_files $uri $uri/ /index.php?$query_string; } location ~ .php$ { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } } EOF # 重启Nginx使配置生效 sudo systemctl restart nginx # 测试配置是否正确 sudo nginx -t 

3.2 网站文件上传

3.2.1 使用SCP上传文件

# 在本地计算机上执行 scp -r /path/to/your/website/* deployer@your-server-ip:/var/www/example.com/ 

3.2.2 使用Git部署网站

# 在服务器上安装Git sudo yum install -y git # 克隆网站代码 cd /var/www/example.com sudo git clone https://github.com/yourusername/yourrepository.git . # 设置正确的文件权限 sudo chown -R apache:apache /var/www/example.com # Apache sudo chown -R nginx:nginx /usr/share/nginx/example.com # Nginx sudo chmod -R 755 /var/www/example.com 

3.3 数据库配置

# 登录MySQL/MariaDB mysql -u root -p # 创建数据库 CREATE DATABASE example_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; # 创建数据库用户并授权 CREATE USER 'example_user'@'localhost' IDENTIFIED BY 'strong_password'; GRANT ALL PRIVILEGES ON example_db.* TO 'example_user'@'localhost'; FLUSH PRIVILEGES; EXIT; # 导入数据库备份 mysql -u example_user -p example_db < /path/to/your/database_backup.sql 

3.4 网站配置文件修改

以WordPress为例:

# 复制配置文件 cd /var/www/example.com cp wp-config-sample.php wp-config.php # 编辑配置文件 vim wp-config.php # 修改以下内容 define('DB_NAME', 'example_db'); define('DB_USER', 'example_user'); define('DB_PASSWORD', 'strong_password'); define('DB_HOST', 'localhost'); # 添加安全密钥(可以从https://api.wordpress.org/secret-key/1.1/salt/获取) define('AUTH_KEY', 'put your unique phrase here'); define('SECURE_AUTH_KEY', 'put your unique phrase here'); define('LOGGED_IN_KEY', 'put your unique phrase here'); define('NONCE_KEY', 'put your unique phrase here'); define('AUTH_SALT', 'put your unique phrase here'); define('SECURE_AUTH_SALT', 'put your unique phrase here'); define('LOGGED_IN_SALT', 'put your unique phrase here'); define('NONCE_SALT', 'put your unique phrase here'); 

4. 安全加固

4.1 防火墙高级配置

# 查看当前防火墙规则 sudo firewall-cmd --list-all # 限制SSH访问(仅允许特定IP) sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="YOUR_IP_ADDRESS" service name="ssh" accept' sudo firewall-cmd --permanent --remove-service=ssh sudo firewall-cmd --reload # 防止DDoS攻击 sudo firewall-cmd --permanent --direct --add-rule ipv4 filter INPUT 0 -p tcp --dport 80 -m connlimit --connlimit-above 100 -j DROP sudo firewall-cmd --permanent --direct --add-rule ipv4 filter INPUT 0 -p tcp --dport 443 -m connlimit --connlimit-above 100 -j DROP sudo firewall-cmd --reload # 安装fail2ban防止暴力破解 sudo yum install -y fail2ban sudo systemctl start fail2ban sudo systemctl enable fail2ban # 配置fail2ban sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local sudo tee -a /etc/fail2ban/jail.local << EOF [sshd] enabled = true bantime = 1h findtime = 10m maxretry = 3 EOF sudo systemctl restart fail2ban 

4.2 SSL证书配置

4.2.1 使用Let’s Encrypt免费SSL证书

# 安装Certbot sudo yum install -y certbot python2-certbot-apache # Apache sudo yum install -y certbot python2-certbot-nginx # Nginx # 获取并安装SSL证书 sudo certbot --apache -d example.com -d www.example.com # Apache sudo certbot --nginx -d example.com -d www.example.com # Nginx # 测试自动续期 sudo certbot renew --dry-run # 设置自动续期 sudo crontab -e # 添加以下行(每月检查并续期证书) 0 0 1 * * /usr/bin/certbot renew --quiet 

4.2.2 强制HTTPS重定向

Apache配置:

# 编辑虚拟主机配置文件 sudo vim /etc/httpd/conf.d/example.com.conf # 添加以下内容 <VirtualHost *:80> ServerName example.com ServerAlias www.example.com Redirect permanent / https://example.com/ </VirtualHost> <VirtualHost *:443> ServerName example.com ServerAlias www.example.com DocumentRoot /var/www/example.com ErrorLog /var/log/httpd/example.com-error.log CustomLog /var/log/httpd/example.com-access.log combined SSLEngine on SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem SSLCertificateChainFile /etc/letsencrypt/live/example.com/chain.pem # 安全头部设置 <IfModule mod_headers.c> Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains" Header always set X-Content-Type-Options "nosniff" Header always set X-Frame-Options "SAMEORIGIN" Header always set X-XSS-Protection "1; mode=block" </IfModule> </VirtualHost> # 重启Apache sudo systemctl restart httpd 

Nginx配置:

# 编辑虚拟主机配置文件 sudo vim /etc/nginx/conf.d/example.com.conf # 修改为以下内容 server { listen 80; server_name example.com www.example.com; return 301 https://example.com$request_uri; } server { listen 443 ssl http2; server_name example.com www.example.com; root /usr/share/nginx/example.com; index index.php index.html index.htm; ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384'; ssl_prefer_server_ciphers off; # 安全头部设置 add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; add_header X-Content-Type-Options "nosniff" always; add_header X-Frame-Options "SAMEORIGIN" always; add_header X-XSS-Protection "1; mode=block" always; access_log /var/log/nginx/example.com-access.log; error_log /var/log/nginx/example.com-error.log; location / { try_files $uri $uri/ /index.php?$query_string; } location ~ .php$ { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } } # 重启Nginx sudo systemctl restart nginx 

4.3 安全插件和工具

4.3.1 安装ModSecurity(Web应用防火墙)

# 安装ModSecurity sudo yum install -y mod_security # 下载OWASP核心规则集 cd /etc/httpd/modsecurity.d sudo wget https://github.com/SpiderLabs/owasp-modsecurity-crs/archive/v3.3.0.tar.gz sudo tar -xvzf v3.3.0.tar.gz sudo mv owasp-modsecurity-crs-3.3.0/crs-setup.conf . sudo mv owasp-modsecurity-crs-3.3.0/rules/ . sudo rm -rf v3.3.0.tar.gz owasp-modsecurity-crs-3.3.0 # 配置ModSecurity sudo cp /etc/httpd/modsecurity.d/modsecurity.conf-recommended /etc/httpd/modsecurity.d/modsecurity.conf sudo sed -i 's/SecRuleEngine DetectionOnly/SecRuleEngine On/' /etc/httpd/modsecurity.d/modsecurity.conf # 重启Apache sudo systemctl restart httpd 

4.3.2 安装ClamAV(防病毒软件)

# 安装EPEL仓库 sudo yum install -y epel-release # 安装ClamAV sudo yum install -y clamav clamav-update # 更新病毒数据库 sudo freshclam # 创建定时任务更新病毒数据库 sudo crontab -e # 添加以下行(每天更新病毒数据库) 0 3 * * * /usr/bin/freshclam # 扫描网站目录 sudo clamscan -r /var/www/example.com 

5. 性能优化

5.1 PHP优化

# 编辑PHP配置文件 sudo cp /etc/php.ini /etc/php.ini.bak sudo vim /etc/php.ini # 修改以下参数(根据服务器配置调整) memory_limit = 256M max_execution_time = 300 upload_max_filesize = 64M post_max_size = 64M max_input_vars = 3000 # 配置OPcache sudo tee -a /etc/php.d/10-opcache.ini << EOF opcache.enable=1 opcache.memory_consumption=128 opcache.interned_strings_buffer=8 opcache.max_accelerated_files=4000 opcache.revalidate_freq=60 opcache.fast_shutdown=1 opcache.enable_file_override=0 opcache.validate_timestamps=1 EOF # 重启PHP-FPM或Apache sudo systemctl restart php-fpm # LNMP环境 sudo systemctl restart httpd # LAMP环境 

5.2 数据库优化

# 编辑MySQL/MariaDB配置文件 sudo cp /etc/my.cnf /etc/my.cnf.bak sudo vim /etc/my.cnf # 添加以下内容(根据服务器配置调整) [mysqld] innodb_buffer_pool_size = 1G innodb_log_file_size = 256M innodb_log_buffer_size = 8M innodb_flush_log_at_trx_commit = 2 innodb_flush_method = O_DIRECT innodb_file_per_table = 1 query_cache_type = 1 query_cache_size = 128M query_cache_limit = 2M max_connections = 200 thread_cache_size = 8 table_open_cache = 2000 # 重启MySQL/MariaDB sudo systemctl restart mariadb 

5.3 Web服务器优化

5.3.1 Apache优化

# 编辑Apache配置文件 sudo cp /etc/httpd/conf/httpd.conf /etc/httpd/conf/httpd.conf.bak sudo vim /etc/httpd/conf/httpd.conf # 修改以下参数(根据服务器配置调整) KeepAlive On MaxKeepAliveRequests 100 KeepAliveTimeout 5 <IfModule mpm_prefork_module> StartServers 5 MinSpareServers 5 MaxSpareServers 10 MaxRequestWorkers 150 MaxConnectionsPerChild 0 </IfModule> # 启用压缩模块 sudo sed -i 's/#LoadModule deflate_module modules/mod_deflate.so/LoadModule deflate_module modules/mod_deflate.so/' /etc/httpd/conf/httpd.conf # 添加压缩配置 sudo tee /etc/httpd/conf.d/deflate.conf << EOF <IfModule mod_deflate.c> AddOutputFilterByType DEFLATE text/plain AddOutputFilterByType DEFLATE text/html AddOutputFilterByType DEFLATE text/xml AddOutputFilterByType DEFLATE text/css AddOutputFilterByType DEFLATE application/xml AddOutputFilterByType DEFLATE application/xhtml+xml AddOutputFilterByType DEFLATE application/rss+xml AddOutputFilterByType DEFLATE application/javascript AddOutputFilterByType DEFLATE application/x-javascript </IfModule> EOF # 启用缓存模块 sudo sed -i 's/#LoadModule expires_module modules/mod_expires.so/LoadModule expires_module modules/mod_expires.so/' /etc/httpd/conf/httpd.conf # 添加缓存配置 sudo tee /etc/httpd/conf.d/expires.conf << EOF <IfModule mod_expires.c> ExpiresActive On ExpiresByType text/css "access plus 1 year" ExpiresByType application/javascript "access plus 1 year" ExpiresByType image/jpg "access plus 1 year" ExpiresByType image/jpeg "access plus 1 year" ExpiresByType image/gif "access plus 1 year" ExpiresByType image/png "access plus 1 year" ExpiresByType image/svg+xml "access plus 1 year" ExpiresByType image/x-icon "access plus 1 year" </IfModule> EOF # 重启Apache sudo systemctl restart httpd 

5.3.2 Nginx优化

# 编辑Nginx配置文件 sudo cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak sudo vim /etc/nginx/nginx.conf # 修改以下参数(根据服务器配置调整) user nginx; worker_processes auto; worker_rlimit_nofile 65535; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 2048; multi_accept on; use epoll; } http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; server_tokens off; client_max_body_size 64M; gzip on; gzip_disable "msie6"; gzip_vary on; gzip_proxied any; gzip_comp_level 6; gzip_buffers 16 8k; gzip_http_version 1.1; gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript application/vnd.ms-fontobject application/x-font-ttf font/opentype image/svg+xml image/x-icon; include /etc/nginx/conf.d/*.conf; } # 重启Nginx sudo systemctl restart nginx 

5.4 缓存配置

5.4.1 安装Redis缓存

# 安装EPEL仓库和Remi仓库 sudo yum install -y epel-release sudo yum install -y https://rpms.remirepo.net/enterprise/remi-release-7.rpm # 安装Redis sudo yum-config-manager --enable remi sudo yum install -y redis # 启动Redis并设置开机自启 sudo systemctl start redis sudo systemctl enable redis # 配置Redis sudo cp /etc/redis.conf /etc/redis.conf.bak sudo vim /etc/redis.conf # 修改以下参数 maxmemory 256mb maxmemory-policy allkeys-lru save 900 1 save 300 10 save 60 10000 # 重启Redis sudo systemctl restart redis # 安装PHP Redis扩展 sudo yum install -y php-pecl-redis # 重启PHP-FPM或Apache sudo systemctl restart php-fpm # LNMP环境 sudo systemctl restart httpd # LAMP环境 

5.4.2 配置WordPress使用Redis缓存

# 安装Redis对象缓存插件 cd /var/www/example.com/wp-content/plugins sudo wget https://downloads.wordpress.org/plugin/redis-cache.2.0.20.zip sudo unzip redis-cache.2.0.20.zip sudo rm redis-cache.2.0.20.zip sudo chown -R apache:apache redis-cache # Apache sudo chown -R nginx:nginx redis-cache # Nginx # 在WordPress中启用Redis缓存 # 1. 登录WordPress后台 # 2. 安装并启用Redis Object Cache插件 # 3. 点击"Enable Object Cache"按钮 # 或者通过wp-cli启用(如果已安装) wp plugin install redis-cache --activate --path=/var/www/example.com wp redis enable --path=/var/www/example.com 

5.5 CDN配置

# 这里以Cloudflare为例,说明如何配置CDN # 1. 注册Cloudflare账号并添加网站 # 2. 按照Cloudflare提示更新域名服务器 # 3. 配置DNS记录 # 4. 启用CDN和缓存 # 5. 配置SSL(Full或Full strict模式) # 6. 配置防火墙规则和安全设置 # 在WordPress中安装Cloudflare插件 cd /var/www/example.com/wp-content/plugins sudo wget https://downloads.wordpress.org/plugin/cloudflare.4.9.0.zip sudo unzip cloudflare.4.9.0.zip sudo rm cloudflare.4.9.0.zip sudo chown -R apache:apache cloudflare # Apache sudo chown -R nginx:nginx cloudflare # Nginx # 在WordPress中启用Cloudflare插件 # 1. 登录WordPress后台 # 2. 安装并启用Cloudflare插件 # 3. 输入Cloudflare API凭据进行连接 

6. 常见问题解决

6.1 连接问题

6.1.1 无法访问网站

问题:浏览器显示”无法访问此网站”或”连接超时”。

解决方案

# 检查Web服务器状态 sudo systemctl status httpd # Apache sudo systemctl status nginx # Nginx # 如果未运行,尝试启动 sudo systemctl start httpd # Apache sudo systemctl start nginx # Nginx # 检查防火墙状态 sudo firewall-cmd --list-all # 确保HTTP和HTTPS端口已开放 sudo firewall-cmd --permanent --add-service=http sudo firewall-cmd --permanent --add-service=https sudo firewall-cmd --reload # 检查Web服务器错误日志 sudo tail -n 50 /var/log/httpd/error_log # Apache sudo tail -n 50 /var/log/nginx/error.log # Nginx # 检查SELinux状态(如果启用) sudo getenforce # 如果SELinux为Enforcing,可能需要调整策略 sudo setsebool -P httpd_can_network_connect 1 sudo setsebool -P httpd_can_network_connect_db 1 sudo setsebool -P httpd_execmem 1 

6.1.2 数据库连接错误

问题:网站显示”建立数据库连接时出错”。

解决方案

# 检查数据库状态 sudo systemctl status mariadb # 如果未运行,尝试启动 sudo systemctl start mariadb # 检查数据库错误日志 sudo tail -n 50 /var/log/mariadb/mariadb.log # 尝试连接数据库 mysql -u root -p # 检查数据库用户和权限 SELECT user, host FROM mysql.user; SHOW GRANTS FOR 'example_user'@'localhost'; # 重置数据库用户密码(如果需要) ALTER USER 'example_user'@'localhost' IDENTIFIED BY 'new_password'; FLUSH PRIVILEGES; # 检查WordPress配置文件中的数据库设置 vim /var/www/example.com/wp-config.php # 确保DB_NAME, DB_USER, DB_PASSWORD, DB_HOST设置正确 

6.2 性能问题

6.2.1 网站加载缓慢

问题:网站加载时间过长,响应缓慢。

解决方案

# 检查系统资源使用情况 top htop free -h df -h # 检查Web服务器进程数 ps aux | grep httpd # Apache ps aux | grep nginx # Nginx # 检查数据库性能 mysql -u root -p SHOW PROCESSLIST; SHOW STATUS LIKE 'Threads%'; SHOW STATUS LIKE 'Connections%'; EXIT; # 启用查询日志(临时) vim /etc/my.cnf # 添加以下内容 [mysqld] slow_query_log = 1 slow_query_log_file = /var/log/mysql/slow.log long_query_time = 2 # 重启MySQL sudo systemctl restart mariadb # 分析慢查询日志 sudo mysqldumpslow /var/log/mysql/slow.log # 检查PHP错误日志 sudo tail -n 50 /var/log/php-fpm/error.log sudo tail -n 50 /var/log/httpd/error_log # 使用Web性能分析工具(如WebPageTest, GTmetrix)分析网站 

6.2.2 高负载问题

问题:服务器负载过高,网站响应缓慢或无响应。

解决方案

# 查看系统负载 uptime top # 查看CPU使用情况 cat /proc/cpuinfo grep 'model name' /proc/cpuinfo | wc -l # 查看内存使用情况 free -h cat /proc/meminfo # 查看磁盘I/O iostat -x 1 5 vmstat 1 5 # 查看网络连接 netstat -an | grep :80 | wc -l netstat -an | grep :443 | wc -l # 查看Web服务器连接数 sudo apachectl status # Apache sudo systemctl status nginx # Nginx # 查看数据库连接数 mysql -u root -p SHOW STATUS LIKE 'Threads_connected'; SHOW STATUS LIKE 'Max_used_connections'; EXIT; # 调整Web服务器配置(参考5.3节) # 调整数据库配置(参考5.2节) # 考虑使用负载均衡或增加服务器资源 

6.3 安全问题

6.3.1 网站被黑或被植入恶意代码

问题:网站显示异常内容,被重定向到其他网站,或被搜索引擎标记为危险网站。

解决方案

# 备份当前网站(如果可能) sudo tar -czf /backup/website-$(date +%Y%m%d).tar.gz /var/www/example.com # 扫描恶意软件 sudo freshclam sudo clamscan -r --infected --remove /var/www/example.com # 检查文件完整性 find /var/www/example.com -type f -exec md5sum {} ; > /tmp/filesums.txt # 检查可疑文件 find /var/www/example.com -name "*.php" -exec grep -l "base64_decode|eval|gzinflate|shell_exec|passthru|system" {} ; # 检查最近修改的文件 find /var/www/example.com -type f -mtime -7 # 清理网站 # 1. 从干净的备份恢复 # 或 # 2. 手动清理受感染的文件 # 更新所有软件 sudo yum update -y # 更新WordPress核心、插件和主题 wp core update --path=/var/www/example.com wp plugin update --all --path=/var/www/example.com wp theme update --all --path=/var/www/example.com # 加强安全措施(参考第4节) 

6.3.2 DDoS攻击

问题:服务器遭受大量请求,导致服务不可用。

解决方案

# 检查网络连接 netstat -an | grep :80 | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -nr | head # 使用fail2ban封禁恶意IP sudo tee -a /etc/fail2ban/jail.local << EOF [http-ddos] enabled = true port = http,https filter = http-ddos logpath = /var/log/httpd/access_log # Apache # logpath = /var/log/nginx/access.log # Nginx maxretry = 100 findtime = 60 bantime = 3600 EOF # 创建过滤器规则 sudo tee /etc/fail2ban/filter.d/http-ddos.conf << EOF [Definition] failregex = ^<HOST> -.*"(GET|POST).* ignoreregex = EOF # 重启fail2ban sudo systemctl restart fail2ban # 使用iptables限制连接频率 sudo iptables -A INPUT -p tcp --dport 80 -m connlimit --connlimit-above 100 -j DROP sudo iptables -A INPUT -p tcp --dport 443 -m connlimit --connlimit-above 100 -j DROP # 安装并配置ModSecurity(参考4.3.1节) # 考虑使用CDN服务(如Cloudflare)缓解DDoS攻击 

6.4 文件权限问题

6.4.1 权限错误导致网站无法正常工作

问题:网站显示”403 Forbidden”错误或无法上传文件。

解决方案

# 检查文件权限 ls -la /var/www/example.com # 设置正确的文件所有者和权限 sudo chown -R apache:apache /var/www/example.com # Apache sudo chown -R nginx:nginx /usr/share/nginx/example.com # Nginx sudo find /var/www/example.com -type d -exec chmod 755 {} ; sudo find /var/www/example.com -type f -exec chmod 644 {} ; # 设置特定目录的可写权限(如上传目录) sudo chmod -R 755 /var/www/example.com/wp-content/uploads # 检查SELinux上下文 ls -Z /var/www/example.com # 设置正确的SELinux上下文 sudo semanage fcontext -a -t httpd_sys_content_t "/var/www/example.com(/.*)?" sudo restorecon -Rv /var/www/example.com # 允许Web服务器写入特定目录 sudo setsebool -P httpd_unified 1 

7. 总结

本教程详细介绍了在CentOS服务器上部署网站的完整流程,从环境配置到站点上线,涵盖了LAMP和LNMP两种主流环境的搭建,网站文件上传和数据库配置,安全加固措施,性能优化策略,以及常见问题的解决方案。

通过遵循本教程的步骤,您可以搭建一个稳定、安全、高效的网站平台。但请记住,网站部署是一个持续的过程,需要定期更新软件、监控系统性能、备份数据,并根据实际需求调整配置。

希望本教程能帮助您顺利完成CentOS服务器上的网站部署工作。如果在实际操作中遇到问题,可以参考第6节的常见问题解决方案,或寻求专业技术支持。