温馨提示×

ubuntu lnmp 如何配置

小樊
34
2026-10-24 14:50:24
栏目: 智能运维

下面给你一份在 Ubuntu 上配置 LNMP(Linux + Nginx + MySQL/MariaDB + PHP) 的实用指南,适用于 Ubuntu 20.04 / 22.04,PHP 以 PHP 8.1 为例(可按需替换版本)。


一、更新系统

sudo apt update
sudo apt upgrade -y

二、安装 Nginx

sudo apt install nginx -y

启动并设置开机自启:

sudo systemctl start nginx
sudo systemctl enable nginx

测试:

curl http://localhost

三、安装 MySQL / MariaDB

方式一:MySQL

sudo apt install mysql-server -y
sudo mysql_secure_installation

方式二:MariaDB(推荐轻量)

sudo apt install mariadb-server -y
sudo mysql_secure_installation

启动:

sudo systemctl start mysql
sudo systemctl enable mysql

四、安装 PHP

安装 PHP 及 Nginx 所需模块

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 服务名(示例为 8.1):

sudo systemctl status php8.1-fpm

五、配置 Nginx 支持 PHP

1. 创建网站目录

sudo mkdir -p /var/www/example.com
sudo chown -R $USER:$USER /var/www/example.com

2. 创建测试文件

echo "<?php phpinfo(); ?>" | sudo tee /var/www/example.com/index.php

3. 配置 Nginx 虚拟主机

sudo nano /etc/nginx/sites-available/example.com

示例配置:

server {
    listen 80;
    server_name example.com www.example.com;

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

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

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

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

4. 启用站点

sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx

六、防火墙(如有启用)

sudo ufw allow 'Nginx Full'

七、测试 LNMP

浏览器访问:

http://服务器IP

或

http://example.com

看到 phpinfo() 页面即配置成功。


八、常见问题

1. 502 Bad Gateway

  • 检查 PHP-FPM 是否运行
sudo systemctl status php8.1-fpm
  • 确认 fastcgi_pass 的 sock 路径正确

2. 修改 PHP 配置

sudo nano /etc/php/8.1/fpm/php.ini

修改后:

sudo systemctl restart php8.1-fpm

九、可选(生产环境)

  • 配置 HTTPS(Let’s Encrypt)
  • 禁用 phpinfo
  • 使用 opcache
  • 限制 PHP 执行目录

如果你需要:

  • Ubuntu + Docker LNMP
  • 一键脚本(如 lnmp.org)
  • 多 PHP 版本共存
  • WordPress / Laravel 配置

告诉我你的使用场景,我可以直接给你对应配置。

0 踩