温馨提示×

LNMP在Debian如何配置

小樊
46
2026-07-02 04:05:12
栏目: 智能运维

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 start nginx
sudo systemctl enable nginx

验证

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


三、安装 MariaDB(MySQL 替代)

sudo apt install mariadb-server -y

初始化数据库安全设置

sudo mysql_secure_installation

按提示操作:

  • 设置 root 密码
  • 删除匿名用户
  • 禁止 root 远程登录
  • 删除 test 数据库

登录测试

sudo mysql -u root -p

四、安装 PHP(FastCGI)

Debian 默认仓库 PHP 版本较新:

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

sudo systemctl start php-fpm
sudo systemctl enable php-fpm

注意:PHP-FPM 服务名可能是 php8.2-fpm,可用:

systemctl status php*-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/php-fpm.sock;
    }

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

检查并重启 Nginx

sudo nginx -t
sudo systemctl restart nginx

六、测试 PHP

创建测试文件:

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

浏览器访问:

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

✅ 看到 PHP 信息页面即成功。


七、配置防火墙(如有 UFW)

sudo ufw allow 80
sudo ufw allow 443
sudo ufw reload

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

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

九、常见目录总结

组件 路径
Nginx 配置 /etc/nginx/
网站根目录 /var/www/html
PHP-FPM /etc/php/*/fpm/
MariaDB /etc/mysql/

十、常见问题排查

  • 502 Bad Gateway:PHP-FPM 未启动或 sock 路径错误
  • 403 Forbidden:目录权限或 index 文件缺失
  • PHP 不解析:Nginx 未正确配置 fastcgi_pass

如果你需要:

  • Debian + Docker LNMP
  • 多站点配置
  • 生产环境优化
  • LNMP 一键脚本

可以直接告诉我你的使用场景。

0