温馨提示×

LNMP环境如何快速配置

小樊
42
2026-07-23 04:40:52
栏目: 编程语言

LNMP(Linux + Nginx + MySQL/MariaDB + PHP) 环境下,快速配置通常有两种方式:一键脚本(最快)手动配置(更可控)。下面按常见场景给你一个实用速查方案。


一、最快方式:使用 LNMP 一键安装包(推荐新手/快速部署)

1️⃣ 安装 LNMP(以 CentOS 7/8 为例)

yum install -y wget
wget http://soft.vpser.net/lnmp/lnmp2.0.tar.gz
tar -xzf lnmp2.0.tar.gz
cd lnmp2.0
./install.sh lnmp

安装过程中会提示:

  • MySQL 版本
  • PHP 版本
  • Nginx 版本

推荐组合(稳定)

  • MySQL 5.7 / MariaDB 10.6
  • PHP 7.4 / 8.1
  • Nginx 1.24+

安装完成后:

lnmp status

2️⃣ 创建网站(自动配置 Nginx + PHP)

lnmp vhost add

按提示输入:

  • 域名(如 example.com
  • 网站目录(默认 /home/wwwroot/example.com
  • 是否开启 SSL(Let’s Encrypt)
  • 是否开启伪静态(如 WordPress)

✅ 自动完成:

  • Nginx 虚拟主机
  • PHP-FPM 配置
  • SSL 证书申请

二、手动配置 LNMP(适合生产环境)

1️⃣ 安装 Nginx

CentOS

yum install -y nginx
systemctl enable nginx
systemctl start nginx

Ubuntu

apt update
apt install -y nginx

2️⃣ 安装 MySQL / MariaDB

MySQL

yum install -y mysql-server
systemctl start mysqld
mysql_secure_installation

MariaDB(推荐)

yum install -y mariadb mariadb-server
systemctl start mariadb
mysql_secure_installation

3️⃣ 安装 PHP(PHP-FPM)

yum install -y php php-fpm php-mysql php-json php-gd php-mbstring
systemctl start php-fpm
systemctl enable php-fpm

⚠️ 注意 PHP-FPM 监听方式:

  • 127.0.0.1:9000
  • unix:/run/php-fpm/www.sock

4️⃣ 配置 Nginx 支持 PHP

编辑站点配置:

vim /etc/nginx/conf.d/example.conf

示例配置:

server {
    listen 80;
    server_name example.com;
    root /var/www/example;
    index index.php index.html;

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

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

重载 Nginx:

nginx -t
systemctl reload nginx

三、常见快速优化(必做)

✅ PHP-FPM 优化

pm = dynamic
pm.max_children = 50
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 20

✅ Nginx 安全头

add_header X-Frame-Options SAMEORIGIN;
add_header X-Content-Type-Options nosniff;

✅ 开启 HTTPS(Let’s Encrypt)

yum install -y certbot python3-certbot-nginx
certbot --nginx -d example.com

四、常见问题速查

问题 原因
访问 PHP 下载 Nginx 未解析 PHP
502 Bad Gateway PHP-FPM 未启动
403 Forbidden 目录权限问题
404 伪静态失效 try_files 未配置

五、推荐组合(稳定 + 高性能)

生产环境

CentOS 7/8 + Nginx + MariaDB + PHP 8.1

WordPress / Laravel

LNMP 一键包 + PHP 8.0+

如果你愿意,我可以根据你的 系统版本(CentOS / Ubuntu)用途(WordPress / Laravel / API) 给你一份 定制版 LNMP 配置方案

0