一、LNMP环境简介
LNMP是指Linux+Nginx+MySQL+PHP组成的网站服务器架构,是目前搭建WordPress等PHP程序的常用环境组合。相较于传统的LAMP(Apache代替Nginx),LNMP架构具有资源占用少、并发能力强、配置灵活等优势。
二、准备工作
在开始搭建前,您需要准备:
- 一台Linux服务器(推荐CentOS 7/8或Ubuntu 18.04/20.04)
- 服务器root权限或sudo权限账户
- 已解析到服务器IP的域名(可选)
- 基本的Linux命令行操作知识
三、LNMP环境安装
1. 安装Nginx
对于CentOS系统:
yum install epel-release -y
yum install nginx -y
systemctl start nginx
systemctl enable nginx
对于Ubuntu系统:
apt update
apt install nginx -y
systemctl start nginx
systemctl enable nginx
2. 安装MySQL/MariaDB
CentOS安装MariaDB:
yum install mariadb-server mariadb -y
systemctl start mariadb
systemctl enable mariadb
mysql_secure_installation
Ubuntu安装MySQL:
apt install mysql-server -y
systemctl start mysql
systemctl enable mysql
mysql_secure_installation
3. 安装PHP
CentOS 7安装PHP 7.4:
yum install -y http://rpms.remirepo.net/enterprise/remi-release-7.rpm
yum install -y yum-utils
yum-config-manager --enable remi-php74
yum install php php-fpm php-mysqlnd php-gd php-mbstring php-xml -y
systemctl start php-fpm
systemctl enable php-fpm
Ubuntu安装PHP 7.4:
apt install php-fpm php-mysql php-gd php-mbstring php-xml -y
systemctl start php7.4-fpm
systemctl enable php7.4-fpm
四、配置WordPress数据库
登录MySQL创建数据库和用户:
CREATE DATABASE wordpress DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;
CREATE USER 'wordpressuser'@'localhost' IDENTIFIED BY 'your_strong_password';
GRANT ALL PRIVILEGES ON wordpress.* TO 'wordpressuser'@'localhost';
FLUSH PRIVILEGES;
EXIT;
五、下载并配置WordPress
cd /tmp
wget https://wordpress.org/latest.tar.gz
tar -xzvf latest.tar.gz
mv wordpress /var/www/html/
chown -R nginx:nginx /var/www/html/wordpress
chmod -R 755 /var/www/html/wordpress
六、配置Nginx虚拟主机
创建配置文件/etc/nginx/conf.d/wordpress.conf
:
server {
listen 80;
server_name yourdomain.com www.yourdomain.com;
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:/var/run/php-fpm/php-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
location ~ /\.ht {
deny all;
}
}
测试并重载Nginx配置:
nginx -t
systemctl reload nginx
七、完成WordPress安装
- 在浏览器访问您的域名或服务器IP
- 按照向导选择语言
- 填写之前创建的数据库信息
- 设置网站标题、管理员账户等信息
- 完成安装并登录后台
八、安全优化建议
- 配置SSL证书(可使用Let’s Encrypt免费证书)
- 限制WordPress后台登录尝试次数
- 定期备份网站和数据库
- 保持WordPress核心、主题和插件更新
- 使用安全插件如Wordfence
九、常见问题解决
- 502 Bad Gateway错误:检查PHP-FPM是否运行,socket路径是否正确
- 文件上传权限问题:确保
wp-content
目录有正确权限 - 内存不足:可编辑
wp-config.php
增加define('WP_MEMORY_LIMIT', '256M');
通过以上步骤,您已成功在LNMP环境下搭建了WordPress网站。后续可根据需求进行主题安装、插件配置等个性化设置。