centos

centos lnmp多站点配置方法

小樊
48
2025-06-22 15:32:03
栏目: 智能运维

在CentOS上配置LNMP(Linux, Nginx, MySQL, PHP)多站点的方法如下:

1. 安装必要的软件包

首先,确保你的系统已经安装了Nginx、MySQL和PHP。你可以使用以下命令来安装这些软件包:

sudo yum install epel-release
sudo yum install nginx mysql-server php-fpm php-mysqlnd

2. 启动并启用服务

启动Nginx和MySQL服务,并设置它们在系统启动时自动运行:

sudo systemctl start nginx
sudo systemctl enable nginx
sudo systemctl start mysqld
sudo systemctl enable mysqld

3. 配置MySQL

登录到MySQL并创建数据库和用户:

sudo mysql -u root -p

在MySQL shell中执行以下命令:

CREATE DATABASE site1;
CREATE USER 'site1user'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON site1.* TO 'site1user'@'localhost';
FLUSH PRIVILEGES;
EXIT;

重复上述步骤为第二个站点创建数据库和用户。

4. 配置Nginx

为每个站点创建一个Nginx配置文件。假设你的站点域名分别是site1.example.comsite2.example.com

站点1配置 (/etc/nginx/conf.d/site1.conf)

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

    root /var/www/site1;
    index index.php index.html index.htm;

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

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

站点2配置 (/etc/nginx/conf.d/site2.conf)

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

    root /var/www/site2;
    index index.php index.html index.htm;

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

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

5. 创建站点目录并设置权限

创建每个站点的根目录并设置适当的权限:

sudo mkdir -p /var/www/site1
sudo mkdir -p /var/www/site2

sudo chown -R nginx:nginx /var/www/site1
sudo chown -R nginx:nginx /var/www/site2

6. 创建PHP文件进行测试

在每个站点的根目录下创建一个简单的PHP文件来测试配置:

站点1 (/var/www/site1/index.php)

<?php
phpinfo();
?>

站点2 (/var/www/site2/index.php)

<?php
phpinfo();
?>

7. 重启Nginx

重启Nginx以应用新的配置:

sudo systemctl restart nginx

8. 配置DNS

确保你的域名解析正确,指向你的服务器IP地址。你可以编辑DNS记录或使用hosts文件进行本地测试。

9. 测试站点

打开浏览器并访问http://site1.example.comhttp://site2.example.com,你应该能看到各自的PHP信息页面。

通过以上步骤,你就可以在CentOS上成功配置LNMP多站点。

0
看了该问题的人还看了