1. 程式人生 > >初識Nginx(二)

初識Nginx(二)

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

重新載入配置檔案
[[email protected] 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;
        }
    }

測試一下就可以了