温馨提示×

如何配置Ubuntu上的LNMP

小樊
37
2025-11-26 14:01:30
栏目: 智能运维

在 Ubuntu 上配置 LNMP 的实操步骤

一 准备与安装

  • 更新系统并安装组件:
    • 更新软件包索引:sudo apt update && sudo apt upgrade -y
    • 安装 Nginx:sudo apt install nginx -y
    • 安装 MySQL:sudo apt install mysql-server -y
    • 安装 PHP 与常用扩展(按需增减):sudo apt install php-fpm php-mysql php-curl php-gd php-mbstring php-xml php-zip -y
  • 启动与开机自启:
    • Nginx:sudo systemctl start nginx && sudo systemctl enable nginx
    • MySQL:sudo systemctl start mysql && sudo systemctl enable mysql
    • PHP-FPM(以实际版本为准,如 php8.1-fpmphp7.4-fpm):sudo systemctl start php8.1-fpm && sudo systemctl enable php8.1-fpm
  • 验证安装:
    • Nginx:浏览器访问 http://服务器IP 出现欢迎页
    • PHP:php -v 显示版本号

二 配置 Nginx 与 PHP-FPM

  • 确认 PHP-FPM 套接字路径(两种常见路径,按实际为准):
    • /var/run/php/php8.1-fpm.sock
    • /run/php/php8.1-fpm.sock
  • 编辑站点配置(示例使用默认站点):sudo nano /etc/nginx/sites-available/default
  • 在 server 块中加入或修改 PHP 处理(注意正则与分号):
    server {
        listen 80;
        server_name your_domain_or_ip;
        root /var/www/html;
        index index.php index.html;
    
        location / {
            try_files $uri $uri/ =404;
        }
    
        location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/run/php/php8.1-fpm.sock;  # 按实际套接字修改
        }
    
        location ~ /\.ht {
            deny all;
        }
    }
    
  • 检查并重载 Nginx:
    • 语法检查:sudo nginx -t
    • 重载:sudo systemctl reload nginx
  • 创建测试页:echo “” | sudo tee /var/www/html/info.php
    • 浏览器访问 http://服务器IP/info.php 应显示 PHP 信息页

三 安全与可选配置

  • MySQL 安全加固:
    • 运行安全脚本:sudo mysql_secure_installation(设置 root 密码、移除匿名用户、禁止 root 远程登录、删除测试库等)
  • 防火墙(如启用 UFW):
    • 放行 HTTP/HTTPS:sudo ufw allow ‘Nginx Full’
    • 放行 SSH:sudo ufw allow ‘OpenSSH’
    • 启用防火墙:sudo ufw enable
  • 远程访问 MySQL(按需开启,务必限制来源与账户权限):
    • 编辑配置:sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf
    • bind-address 改为 0.0.0.0(或注释掉该行)以监听所有地址
    • 重启 MySQL:sudo systemctl restart mysql
    • 授权示例(在 MySQL 中执行):
      CREATE USER 'appuser'@'%' IDENTIFIED BY 'StrongPass!';
      GRANT ALL PRIVILEGES ON your_db.* TO 'appuser'@'%';
      FLUSH PRIVILEGES;
      
  • 获取免费 SSL 证书(Certbot + Nginx):
    • 安装:sudo apt install certbot python3-certbot-nginx -y
    • 申请并自动配置:sudo certbot --nginx -d your_domain.com
    • 按提示选择是否重定向 HTTP 到 HTTPS

四 常见问题排查

  • 502 Bad Gateway / 页面空白:
    • 核对 fastcgi_pass 的套接字路径是否为 /var/run/php/…/run/php/…
    • 确认 php-fpm 服务已启动:sudo systemctl status php8.1-fpm
    • 检查 Nginx 配置语法与重载:sudo nginx -t && sudo systemctl reload nginx
  • 权限问题:
    • 确保 /var/www/html 及子目录对 www-data(Nginx 运行用户)可读,必要时:sudo chown -R www-data:www-data /var/www/html
  • 日志定位:
    • Nginx 错误日志:/var/log/nginx/error.log
    • PHP-FPM 日志:常见路径如 /var/log/php8.1-fpm.log(随版本与配置而异)

0