温馨提示×

Debian LNMP如何安装与配置

小樊
72
2025-03-26 22:29:03
栏目: 智能运维

在Debian系统上安装和配置LNMP(Linux, Nginx, MySQL/MariaDB, PHP)环境,可以按照以下步骤进行:

1. 更新系统包

首先,确保你的系统包是最新的:

sudo apt update
sudo apt upgrade -y

2. 安装Nginx

sudo apt install nginx -y

安装完成后,启动Nginx并设置开机自启:

sudo systemctl start nginx
sudo systemctl enable nginx

3. 安装MySQL/MariaDB

你可以选择安装MySQL或MariaDB。这里以MariaDB为例:

sudo apt install mariadb-server -y

安装完成后,启动MariaDB并设置开机自启:

sudo systemctl start mariadb
sudo systemctl enable mariadb

运行安全脚本以设置root密码和其他安全选项:

sudo mysql_secure_installation

4. 安装PHP

安装PHP及其常用扩展:

sudo apt install php-fpm php-mysql -y

配置PHP-FPM以使用Unix套接字(而不是TCP/IP): 编辑/etc/php/7.4/fpm/pool.d/www.conf文件(根据你的PHP版本调整路径),找到以下行并修改:

;listen = /run/php/php7.4-fpm.sock
listen = /var/run/php/php7.4-fpm.sock

然后重启PHP-FPM服务:

sudo systemctl restart php7.4-fpm

5. 配置Nginx以使用PHP-FPM

编辑Nginx的默认站点配置文件:

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

找到以下部分并进行修改:

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    root /var/www/html;
    index index.php index.html index.htm index.nginx-debian.html;

    server_name _;

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

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

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

保存并退出编辑器,然后测试Nginx配置:

sudo nginx -t

如果没有错误,重新加载Nginx:

sudo systemctl reload nginx

6. 创建一个PHP测试文件

创建一个简单的PHP文件来测试配置:

sudo nano /var/www/html/index.php

添加以下内容:

<?php
phpinfo();
?>

保存并退出编辑器,然后在浏览器中访问你的服务器IP地址或域名,你应该能看到PHP信息页面。

7. 配置防火墙(可选)

如果你使用的是UFW防火墙,可以允许HTTP和HTTPS流量:

sudo ufw allow 'Nginx Full'

至此,你已经在Debian系统上成功安装并配置了LNMP环境。

0