当前位置:   首页安装配置

nginx 配置虚拟主机,实现在一个主机可以访问多个网站的方法

发布日期:2022-01-05 17:23 | 文章来源:脚本之家

在一台主机上,访问不同的网站

通常有两种区分方式:

1.通过监听的端口号

2.通过域名

1.通过端口访问不同的主机:

Nginx的配置文件:

/usr/local/nginx/conf/nginx.conf

Centos文件默认编码格式 latin1

查看编码格式的命令: :set fileencoding

#user nobody;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid    logs/nginx.pid;
events {
  worker_connections 1024;
}
##一个http节点
http {  
  include    mime.types;
  default_type application/octet-stream;
  #log_format main '$remote_addr - $remote_user [$time_local] "$request" '
  #         '$status $body_bytes_sent "$http_referer" '
  #         '"$http_user_age

此时 可以配置多个server,也就是配置了不同的主机

添加虚拟主机:(通过端口号 区别)

server {
    listen    81;
    server_name localhost;
    #charset koi8-r;
    #access_log logs/host.access.log main;
    location / {
      root  html-81;
  #nginx根目录下 新建的html81 文件夹
      index index.html index.htm;
    ``
  }

编辑好文件之后,我们重新加载配置文件

通过命令: ./nginx -s reload

效果:

我们知道,当一个主机上配置多个网站时,我们不可能通过端口号来区分它们,所以接下来 我需要通过域名来区分

2.通过域名区分不同的虚拟主机

什么是域名??

域名就是网址

例如:www.baidu.com

通常我们在访问域名的时候,我们需要通过dns主机解析域名

Dns主机:把域名解析为ip地址。保存的就是域名和ip的映射关系。

一个域名对应一个ip地址,一个ip地址可以被多个域名绑定。

本地测试可以修改hosts文件。

修改window的hosts文件:(C:\Windows\System32\drivers\etc)

可以配置域名和ip的映射关系,如果hosts文件中配置了域名和ip的对应关系,不需要走dns主机!!!!

在刚刚的nginx.conf文件下 继续配置:

server {
    listen    80;
    server_name www.taobao.com;
    #charset koi8-r;
    #access_log logs/host.access.log main;
    location / {
      root  html-taobao;
      index index.html index.htm;
    }
  }
  server {
    listen    80;
    server_name www.baidu.com;
    #charset koi8-r;
    #access_log logs/host.access.log main;
    location / {
      root  html-baidu;
      index index.html index.htm;
    }
  }
}

域名的配置:

192.168.25.148 www.test.com
192.168.25.148 www.yiyou.com

重启nginx服务

观察下效果:

以上这篇nginx 配置虚拟主机,实现在一个主机可以访问多个网站的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持本站。

联系我们
关于使用场景和技术架构的更多咨询,请联系我们的销售和技术支持团队。
Yingsoo Host

在线
客服

在线客服:7*24小时在线

客服
热线

400-630-3752
7*24小时客服服务热线

关注
微信

关注官方微信
顶部