温馨提示×

LNMP环境如何添加网站

小樊
39
2026-07-10 22:55:10
栏目: 云计算

LNMP 环境(Linux + Nginx + MySQL + PHP) 中“添加网站”,通常指 新建一个站点(虚拟主机),包含:
Nginx 站点配置 + 网站目录 +(可选)数据库 +(可选)PHP 支持。
下面按 通用标准做法 一步一步说明,适用于 LNMP 一键包 / 手工编译环境


一、准备工作

假设你已经具备:

  • Linux 服务器(CentOS / Ubuntu / Debian)
  • 已安装 LNMP
  • 域名已解析到服务器 IP(如 example.com

二、创建网站目录

mkdir -p /www/wwwroot/example.com
chown -R www:www /www/wwwroot/example.com
chmod -R 755 /www/wwwroot/example.com

⚠️ 说明:

  • www 是 Nginx/PHP 的运行用户(视环境可能是 nginxphp-fpm
  • 目录路径可自行调整

测试页面(可选)

echo "<?php phpinfo(); ?>" > /www/wwwroot/example.com/index.php

三、创建 Nginx 站点配置文件

1️⃣ 新建配置文件

vim /etc/nginx/conf.d/example.com.conf

2️⃣ 推荐配置(PHP 支持)

server {
    listen 80;
    server_name example.com www.example.com;
    root /www/wwwroot/example.com;
    index index.php index.html index.htm;

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

    location ~ \.php$ {
        fastcgi_pass   unix:/run/php/php-fpm.sock;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }

    location ~ /\. {
        deny all;
    }
}

⚠️ 注意:

  • fastcgi_pass 路径需根据你的 PHP-FPM 实际配置调整:
    • /run/php/php-fpm.sock
    • 127.0.0.1:9000

四、启用站点并测试配置

1️⃣ 检查 Nginx 配置

nginx -t

2️⃣ 重载 Nginx

systemctl reload nginx

五、配置数据库(可选)

1️⃣ 登录 MySQL

mysql -uroot -p

2️⃣ 创建数据库和用户

CREATE DATABASE example_db DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

CREATE USER 'example_user'@'localhost' IDENTIFIED BY 'StrongPassword';

GRANT ALL PRIVILEES ON example_db.* TO 'example_user'@'localhost';

FLUSH PRIVILEGES;
EXIT;

六、HTTPS(强烈推荐)

使用 Let’s Encrypt

yum install certbot python3-certbot-nginx -y
# 或
apt install certbot python3-certbot-nginx -y
certbot --nginx -d example.com -d www.example.com

证书会自动续期 ✅


七、LNMP 一键包用户(简化方式)

如果你使用的是 LNMP 一键安装包

lnmp vhost add

按提示输入:

  • 域名
  • 网站目录
  • 是否启用 Rewrite
  • 是否启用 SSL
  • 是否创建数据库

✅ 自动完成 Nginx + PHP + 数据库配置


八、常见问题排查

1️⃣ 403 Forbidden

  • 目录权限错误
  • index 文件不存在

2️⃣ 502 Bad Gateway

  • PHP-FPM 未启动
  • fastcgi_pass 路径错误
systemctl status php-fpm

3️⃣ 网站访问空白

  • PHP 未解析
  • SCRIPT_FILENAME 配置错误

九、总结流程

✅ 创建网站目录
✅ 配置 Nginx 虚拟主机
✅ 检查 PHP-FPM
✅ 配置数据库(可选)
✅ 配置 HTTPS(推荐)


如果你愿意,可以告诉我:

  • 系统版本(CentOS 7/8、Ubuntu 20/22)
  • LNMP 是“一键包”还是“手动搭建”
  • 是否用宝塔 / aaPanel

我可以给你 完全贴合你服务器的配置示例

0