温馨提示×

debian怎么搭建lnmp

小樊
55
2026-07-30 08:06:29
栏目: 智能运维

在 Debian 上搭建 LNMP(Linux + Nginx + MySQL/MariaDB + PHP) 环境,下面是通用、稳定、适合生产环境的做法(以 Debian 11/12 为例)。


一、更新系统

sudo apt update
sudo apt upgrade -y

二、安装 Nginx

sudo apt install nginx -y

启动并设置开机自启:

sudo systemctl enable nginx
sudo systemctl start nginx

验证:

systemctl status nginx

浏览器访问服务器 IP,看到 Welcome to nginx 即成功。


三、安装 MariaDB(推荐替代 MySQL)

sudo apt install mariadb-server -y

初始化安全配置:

sudo mysql_secure_installation

按提示设置 root 密码、删除测试库等。

登录测试:

sudo mysql -u root -p

四、安装 PHP(FastCGI)

Debian 12 默认 PHP 8.2,11 默认 7.4 或 8.2(取决于源)。

sudo apt install php-fpm php-mysql php-cli php-curl php-gd php-mbstring php-xml php-zip -y

查看 PHP 版本:

php -v

确认 php-fpm 运行:

systemctl status php8.2-fpm

(版本号按实际调整)


五、配置 Nginx 支持 PHP

编辑站点配置:

sudo nano /etc/nginx/sites-available/default

示例配置(重点):

server {
    listen 80;
    server_name your_domain_or_ip;

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

    location / {
        try_files $uri $uri/ =404;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php8.2-fpm.sock;
    }

    location ~ /\.ht {
        deny all;
    }
}

测试并重载 Nginx:

sudo nginx -t
sudo systemctl reload nginx

六、测试 PHP 是否正常工作

echo "<?php phpinfo(); ?>" | sudo tee /var/www/html/info.php

浏览器访问:

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

确认能看到 PHP 信息页 ✅
测试完成后删除:

sudo rm /var/www/html/info.php

七、设置目录权限(重要)

sudo chown -R www-data:www-data /var/www/html
sudo chmod -R 755 /var/www/html

八、(可选)开启 HTTPS(Let’s Encrypt)

sudo apt install certbot python3-certbot-nginx -y
sudo certbot --nginx -d your_domain

九、常见排错

1. 502 Bad Gateway

  • php-fpm 未启动
  • fastcgi_pass 路径错误

检查:

ls /run/php/
systemctl status php8.2-fpm

2. PHP 文件被下载

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

十、总结

✅ 已成功搭建:

  • Nginx(Web 服务)
  • MariaDB(数据库)
  • PHP(动态解析)

如果你需要:

  • 指定 PHP 版本
  • 多站点配置
  • Docker / LNMP 一键脚本
  • WordPress / Laravel 环境

可以直接告诉我你的 Debian 版本和使用场景。

0