插件窝 干货文章 CentOS7.3怎么配置Nginx虚拟主机

CentOS7.3怎么配置Nginx虚拟主机

Nginx 配置 sudo example 112    来源:    2025-04-25

CentOS 7.3 配置Nginx虚拟主机指南

在CentOS 7.3上配置Nginx虚拟主机(server blocks)可以让您在一台服务器上托管多个网站。以下是详细步骤:

1. 安装Nginx

如果尚未安装Nginx,请先安装:

sudo yum install epel-release
sudo yum install nginx
sudo systemctl start nginx
sudo systemctl enable nginx

2. 创建网站目录结构

为每个虚拟主机创建单独的目录:

sudo mkdir -p /var/www/example.com/html
sudo mkdir -p /var/www/test.com/html

设置正确的权限:

sudo chown -R $USER:$USER /var/www/example.com/html
sudo chown -R $USER:$USER /var/www/test.com/html
sudo chmod -R 755 /var/www

3. 创建示例页面

为每个网站创建测试页面:

# 第一个网站
echo "<h1>Welcome to Example.com</h1>" > /var/www/example.com/html/index.html

# 第二个网站
echo "<h1>Welcome to Test.com</h1>" > /var/www/test.com/html/index.html

4. 创建虚拟主机配置文件

/etc/nginx/conf.d/目录中为每个网站创建配置文件:

sudo vi /etc/nginx/conf.d/example.com.conf

添加以下内容:

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

    root /var/www/example.com/html;
    index index.html index.htm;

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

    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /usr/share/nginx/html;
    }
}

同样为第二个网站创建配置文件:

sudo vi /etc/nginx/conf.d/test.com.conf

内容类似,只需修改server_name和root路径。

5. 禁用默认配置

sudo mv /etc/nginx/conf.d/default.conf /etc/nginx/conf.d/default.conf.bak

6. 测试并重启Nginx

测试配置是否正确:

sudo nginx -t

如果没有错误,重启Nginx:

sudo systemctl restart nginx

7. 本地测试配置

编辑本地hosts文件(如Windows的C:\Windows\System32\drivers\etc\hosts或Linux的/etc/hosts),添加:

your_server_ip example.com
your_server_ip test.com

然后在浏览器中访问http://example.comhttp://test.com,应该能看到不同的内容。

8. (可选) 配置防火墙

如果启用了防火墙,需要允许HTTP流量:

sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --reload

注意事项

  1. 确保您的域名已正确解析到服务器IP
  2. 生产环境中建议配置SSL证书(使用Let's Encrypt等)
  3. 对于高流量网站,可能需要调整Nginx的性能参数
  4. 定期检查Nginx错误日志:/var/log/nginx/error.log

如需配置HTTPS虚拟主机,可以使用Let's Encrypt的certbot工具自动配置SSL证书和Nginx配置。