网络知识
如何配置centos lnmp虚拟主机
2025-07-13 14:40  点击:7

在CentOS上配置LNMP(Linux, Nginx, MySQL/MariaDB, PHP)虚拟主机的步骤如下:

1. 安装必要的软件包

首先,确保你的系统是最新的,并安装Nginx、MySQL/MariaDB和PHP。

sudo yum update -ysudo yum install epel-release -ysudo yum install nginx mariadb-server php-fpm php-mysqlnd -y
2. 启动并启用服务

启动Nginx和MariaDB服务,并设置它们开机自启。

sudo systemctl start nginxsudo systemctl enable nginxsudo systemctl start mariadbsudo systemctl enable mariadb
3. 配置MariaDB

运行安全脚本以设置MariaDB的root密码和其他安全选项。

sudo mysql_secure_installation

然后创建一个新的数据库和用户,并授予该用户对数据库的访问权限。

CREATE DATAbase your_database_name;CREATE USER 'your_username'@'localhost' IDENTIFIED BY 'your_password';GRANT ALL PRIVILEGES ON your_database_name.* TO 'your_username'@'localhost';FLUSH PRIVILEGES;EXIT;
4. 配置Nginx

创建一个新的Nginx配置文件来定义虚拟主机。

sudo vi /etc/nginx/conf.d/your_domain.conf

在文件中添加以下内容:

server {listen 80;server_name your_domain.com www.your_domain.com;root /var/www/your_domain;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/php-fpm.sock;fastcgi_param script_FILENAME $document_root$fastcgi_script_name;include fastcgi_params;}location ~ /\.ht {deny all;}}

保存并退出编辑器。

5. 创建网站目录

创建一个目录来存放你的网站文件,并设置适当的权限。

sudo mkdir -p /var/www/your_domainsudo chown -R nginx:nginx /var/www/your_domain
6. 配置PHP-FPM

编辑PHP-FPM配置文件以确保它能够正确处理请求。

sudo vi /etc/php-fpm.d/www.conf

找到并修改以下行:

user = nginxgroup = nginx

保存并退出编辑器,然后重启PHP-FPM服务。

sudo systemctl restart php-fpm
7. 测试Nginx配置

测试Nginx配置文件是否有语法错误。

sudo nginx -t

如果没有错误,重新加载Nginx以应用更改。

sudo systemctl reload nginx
8. 更新hosts文件(可选)

如果你在本地测试,可以在/etc/hosts文件中添加你的域名和IP地址。

sudo vi /etc/hosts

添加以下行:

127.0.0.1 your_domain.com www.your_domain.com

保存并退出编辑器。

9. 访问你的网站

现在,你应该可以通过浏览器访问你的域名来查看你的网站了。

http://your_domain.com

以上步骤应该可以帮助你在CentOS上成功配置LNMP虚拟主机。如果有任何问题,请检查相关服务的日志文件以获取更多信息。