LNMP 环境搭建完全指南:Linux + Nginx + MySQL + PHP 从零配置

LNMP(Linux + Nginx + MySQL + PHP)是搭建 PHP 网站最经典的服务器架构。WordPressLaravel、ThinkPHP 等主流 PHP 应用都运行在 LNMP 环境中。本文将从一台纯净的 Linux 服务器开始,逐步完成完整搭建。

一、系统初始化

选择操作系统

推荐使用 Ubuntu 22.04 LTS 或 24.04 LTS。对于生产环境,LTS 版本提供 5 年以上的安全更新支持。

初始安全配置

# 更新系统
apt update && apt upgrade -y

# 创建普通用户
adduser deploy
usermod -aG sudo deploy

# 配置 SSH 密钥登录
ssh-keygen -t ed25519 -C "[email protected]"
# 将公钥添加到 ~/.ssh/authorized_keys

# 禁止 root 登录
sed -i 's/PermitRootLogin yes/PermitRootLogin no/' /etc/ssh/sshd_config
systemctl restart sshd

# 配置防火墙
ufw allow OpenSSH
ufw allow 'Nginx Full'
ufw enable

二、安装 Nginx

# 安装 Nginx
apt install nginx -y

# 验证安装
nginx -v
systemctl status nginx

# 基础配置优化
cat > /etc/nginx/nginx.conf << 'EOF'
user www-data;
worker_processes auto;
worker_rlimit_nofile 65535;

events {
    worker_connections 4096;
    use epoll;
    multi_accept on;
}

http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;
    
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    server_tokens off;
    
    # Gzip 压缩
    gzip on;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml text/x-component;
    gzip_min_length 256;
    gzip_comp_level 5;
    gzip_vary on;
    
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}
EOF

# 创建站点配置
cat > /etc/nginx/sites-available/example.com << 'EOF'
server {
    listen 80;
    server_name example.com www.example.com;
    root /var/www/example.com/public;
    index index.php index.html;
    
    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }
    
    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php8.3-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
    
    location ~ /\.ht {
        deny all;
    }
}
EOF

# 启用站点
ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
nginx -t && systemctl reload nginx

三、安装 MySQL

# 安装 MySQL 8.0
apt install mysql-server -y

# 安全配置
mysql_secure_installation
# 按照提示设置 root 密码、移除匿名用户、禁止远程 root 登录、移除测试数据库

# 创建网站数据库和用户
mysql -u root -p
CREATE DATABASE example_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER 'example_user'@'localhost' IDENTIFIED BY 'strong_password';
GRANT ALL PRIVILEGES ON example_db.* TO 'example_user'@'localhost';
FLUSH PRIVILEGES;
EXIT;

MySQL 性能优化

# /etc/mysql/mysql.conf.d/optimize.cnf
[mysqld]
# InnoDB 设置
innodb_buffer_pool_size = 1G    # 设为可用内存的 60-70%
innodb_log_file_size = 256M
innodb_flush_log_at_trx_commit = 2
innodb_file_per_table = 1

# 连接设置
max_connections = 150
max_allowed_packet = 64M

# 缓存设置
query_cache_type = 0            # MySQL 8.0 已移除查询缓存
tmp_table_size = 64M
max_heap_table_size = 64M

# 字符集
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci

四、安装 PHP

# Ubuntu 24.04 默认 PHP 8.3
apt install php8.3-fpm php8.3-cli php8.3-mysql php8.3-curl \
  php8.3-gd php8.3-mbstring php8.3-xml php8.3-bcmath php8.3-zip \
  php8.3-redis php8.3-opcache -y

# 验证安装
php -v
php -m  # 查看已安装的模块

PHP-FPM 优化

# /etc/php/8.3/fpm/pool.d/www.conf
pm = dynamic
pm.max_children = 50
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 15
pm.max_requests = 500
# /etc/php/8.3/cli/conf.d/99-optimize.ini
memory_limit = 256M
upload_max_filesize = 64M
post_max_size = 64M
max_execution_time = 300
date.timezone = Asia/Shanghai

五、一键安装脚本替代方案

如果不想手动逐项安装,可以使用以下一键脚本:

LNMP.org 一键包

wget https://soft.lnmp.com/lnmp/lnmp2.0.tar.gz
tar zxf lnmp2.0.tar.gz
cd lnmp2.0
./install.sh lnmp

Oneinstack

wget https://oneinstack.com/download/oneinstack-full.tar.gz
tar xzf oneinstack-full.tar.gz
cd oneinstack
./install.sh --nginx_option 1 --php_option 9 --mysql_option 2

六、安全加固

# 配置 Fail2Ban 防止暴力破解
apt install fail2ban -y
cat > /etc/fail2ban/jail.local << 'EOF'
[sshd]
enabled = true
maxretry = 5
bantime = 3600

[nginx-http-auth]
enabled = true
maxretry = 5
bantime = 3600
EOF
systemctl restart fail2ban

# 设置自动安全更新
apt install unattended-upgrades -y
dpkg-reconfigure --priority=low unattended-upgrades

七、性能测试

# 使用 ab 进行压力测试
apt install apache2-utils -y
ab -n 1000 -c 50 http://example.com/

# PHP 性能测试
cat > /var/www/example.com/public/info.php << 'EOF'
<?php
phpinfo();
EOF

16IDC 观察

LNMP 环境是 PHP 建站的基础。对于新手站长,建议先使用 Oneinstack 或 LNMP.org 一键脚本快速搭建,待熟悉后再逐步深入手动配置。内存方面,1GB 服务器即可运行基础 LNMP,2GB 以上可以流畅运行 WordPress 等 CMS。建议选择 16IDC 推荐的 海外服务器方案 以获得最佳性能和稳定性。