初识Nginx(二)

版权声明:Copyright ◎ https://blog.csdn.net/huoliangwu/article/details/84840856

Nginx的应用场景

1、http服务器。Nginx是一个http服务可以独立提供http服务。可以做网页静态服务器。
2、虚拟主机。可以实现在一台服务器虚拟出多个网站。例如个人网站使用的虚拟主机。
3、反向代理,负载均衡。当网站的访问量达到一定程度后,单台服务器不能满足用户的请求时,需要用多台服务器集群可以使用nginx做反向代理。并且多台服务器可以平均分担负载,不会因为某台服务器负载高宕机而某台服务器闲置的情况。

  • 配置虚拟主机
    就是在一台服务器启动多个网站。
    如何区分不同的网站:
    1、域名不同
    2、端口不同

  • 通过端口区分不同虚拟机
    Nginx的配置文件:(安装在/usr/local下)
    /usr/local/nginx/conf/nginx.conf

在这里插入图片描述
所以我们可以配置多个server,配置了多个虚拟主机
添加虚拟主机:
在这里插入图片描述注意需要把nginx下的html目录复制一份
cp html/ htnml-81

重新加载配置文件
[root@localhost nginx]# sbin/nginx -s reload

  • 通过域名区分虚拟主机
    域名就是网站。
    Dns服务器:把域名解析为ip地址。保存的就是域名和ip的映射关系。
    修改window的hosts文件(C:\Windows\System32\drivers\etc)
    192.168.25.148 www.taobao.com
    192.168.25.148 www.baidu.com
  • Nginx的配置
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;
        }
    }
  • 反向代理 负载均衡
    两个域名指向同一台nginx服务器,用户访问不同的域名显示不同的网页内容。
    打个比方: 一台服务器开了两TOMCAT服务器,一台是百度的8080服务器,另一台是新浪的8081服务器.那么用户在浏览器输入www.baidu.com就会连接8080的TOMCAT服务器,输入新浪的网址就自动连接80801的服务器.

  • 反向代理服务器的设置

upstream tomcat1 {
	server 192.168.25.148:8080;
    }
        upstream tomcat2 {
	server 192.168.25.148:8081;
    }
    server {
        listen       80;
        server_name  www.sina.com.cn;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
           proxy_pass   http://tomcat1;
            index  index.html index.htm;
        }
    }

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

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            proxy_pass   http://tomcat2;
            index  index.html index.htm;
        }
    }

测试一下就可以了

猜你喜欢

转载自blog.csdn.net/huoliangwu/article/details/84840856