温馨提示×

centos lnmp如何配置

小樊
38
2026-10-15 00:50:52
栏目: 智能运维

下面给你一个在 CentOS 上配置 LNMP(Linux + Nginx + MySQL/MariaDB + PHP)的通用、可操作教程,适用于 CentOS 7 / 8(CentOS 8 已 EOL,建议用 Rocky/Alma,但步骤基本一致)。


一、基础准备

1. 更新系统

yum update -y

2. 关闭 SELinux(新手建议,生产可酌情开启)

setenforce 0
sed -i 's/SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config

3. 防火墙放行端口

firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --reload

二、安装 Nginx

CentOS 7

yum install -y epel-release
yum install -y nginx

启动并设置开机自启

systemctl start nginx
systemctl enable nginx

浏览器访问服务器 IP,看到 Nginx 欢迎页即成功。


三、安装 MySQL / MariaDB

方案 A:MariaDB(推荐 CentOS)

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

初始化安全配置

mysql_secure_installation

四、安装 PHP

CentOS 7 安装 PHP 7.4(示例)

yum install -y epel-release yum-utils
yum install -y http://rpms.remirepo.net/enterprise/remi-release-7.rpm
yum-config-manager --enable remi-php74
yum install -y php php-fpm php-mysqlnd php-gd php-mbstring php-xml php-json

启动 PHP-FPM

systemctl start php-fpm
systemctl enable php-fpm

五、配置 Nginx 支持 PHP

编辑站点配置

vi /etc/nginx/conf.d/default.conf

示例配置:

server {
    listen 80;
    server_name your_domain_or_ip;

    root /usr/share/nginx/html;
    index index.php index.html;

    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

nginx -t
systemctl reload nginx

六、测试 PHP

echo "<?php phpinfo(); ?>" > /usr/share/nginx/html/info.php

浏览器访问:

http://服务器IP/info.php

看到 PHP 信息页即成功 ✅


七、常见问题

1. 502 Bad Gateway

  • 检查 php-fpm 是否运行
  • 确认 fastcgi_pass 端口(9000 或 unix socket)

2. 页面直接下载 PHP

  • Nginx 未正确解析 PHP
  • 检查 location ~ \.php$ 配置

3. 权限问题

chown -R nginx:nginx /usr/share/nginx/html

八、(可选)一键方案

如果不想手动配置:

  • LNMP 一键安装包(国人常用)
wget http://soft.vpser.net/lnmp/lnmp2.0.tar.gz
tar zxf lnmp2.0.tar.gz
cd lnmp2.0
./install.sh lnmp

如果你告诉我:

  • CentOS 版本(7 / 8 / Stream)
  • PHP 版本需求
  • 是否用域名 / HTTPS

我可以给你更精确的生产级配置。

0 踩