9 10 月, 2025

🧩 一、问题背景

迁移服务器或修改数据库后,我的 WordPress 打开页面提示:

Error establishing a database connection

同时,有时根目录报 403 Forbidden
/wordpress/ 页面却能正常访问。
这说明 WordPress 的数据库配置或 Nginx 设置存在问题。


🔍 二、问题分析

通过一系列排查后,发现了几个关键原因:

  1. wp-config.php 中的数据库信息不匹配
  2. MySQL 用户权限只授权了 localhost,没有给 127.0.0.1
  3. Nginx 配置文件中 root 路径错误
  4. PHP 连接数据库时未正确使用 socket

🔧 三、解决步骤

1️⃣ 修复 MySQL 用户与权限

登录数据库:

mysql -uroot -p

执行:

CREATE DATABASE wordpress DEFAULT CHARSET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER 'wpuser'@'localhost' IDENTIFIED BY 'LH2004lh-';
GRANT ALL PRIVILEGES ON wordpress.* TO 'wpuser'@'localhost';
FLUSH PRIVILEGES;

2️⃣ 编辑 wp-config.php

路径:/var/www/html/wordpress/wp-config.php

define('DB_NAME', 'wordpress');
define('DB_USER', 'wpuser');
define('DB_PASSWORD', 'LH2004lh-');
define('DB_HOST', 'localhost');
define('DB_CHARSET', 'utf8mb4');
define('DB_COLLATE', '');
$table_prefix = 'wp_';
define('WP_DEBUG', false);

3️⃣ 重写 Nginx 配置(/etc/nginx/conf.d/lhws.top.conf)

server {
    listen 80;
    server_name lhws.top www.lhws.top;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    server_name lhws.top www.lhws.top;

    ssl_certificate /etc/letsencrypt/live/lhws.top/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/lhws.top/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

    root /var/www/html/wordpress;
    index index.php index.html index.htm;

    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass unix:/run/php-fpm/www.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }

    error_page 403 /403.html;
    error_page 404 /404.html;
}

4️⃣ 数据库连接测试文件(testdb.php)

<?php
$db_socket = '/var/lib/mysql/mysql.sock';
$conn = new mysqli(null, 'wpuser', 'LH2004lh-', 'wordpress', null, $db_socket);
if ($conn->connect_error) {
    die("❌ 数据库连接失败!<br>错误信息: " . $conn->connect_error);
}
echo "✅ 数据库连接成功!";
$conn->close();
?>

✅ 四、结果验证

  • 访问 https://lhws.top/testdb.php 显示 ✅ 数据库连接成功!
  • WordPress 前台与后台全部恢复正常
  • 403/404 问题消失,HTTPS 强制跳转生效

💡 五、经验总结

  • WordPress 的数据库连接是通过 mysqli,必须确认 socket 与用户权限匹配
  • 推荐使用 localhost + Unix socket(比 TCP 更稳定)
  • Nginx 的 root 路径必须精确指向 WordPress 目录
  • 一定记得在修改后重启服务: systemctl restart nginx systemctl restart php-fpm

✅ 最终结果:
网站完全恢复,数据库连接稳定,HTTPS 正常跳转。
一次从“Error establishing a database connection”到“网站重生”的完整修复!

This entry was posted on 星期四, 9 10 月, 2025 at 8:42 上午 and is filed under Uncategorized. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>