前言 前面提到過, 由nginx來分發請求到tomcat中, 那麼怎麼來區分這些tomcat呢? 我們一般訪問網站的時候, 是不是可以使用 ip : port (127.0.0.1:8080)的方式來訪問, 或者是 功能變數名稱 : port (www.baidu.com:80), 只不過這裡可以不寫埠, ...
前言
前面提到過, 由nginx來分發請求到tomcat中, 那麼怎麼來區分這些tomcat呢?
我們一般訪問網站的時候, 是不是可以使用 ip : port (127.0.0.1:8080)的方式來訪問, 或者是 功能變數名稱 : port (www.baidu.com:80), 只不過這裡可以不寫埠, 這是由於使用了預設的埠.
那麼在nginx分發的時候, 是不是也可以通過 區分 功能變數名稱 和 port 的方式來區分使用tomcat呢?
註: 同一個ip下麵, 可以綁定多個功能變數名稱, 但是一個功能變數名稱, 只能有一個ip. 如果一個ip上面綁定了多個功能變數名稱, 假如 127.0.0.1 綁定了 www.hao123.com 和 www.google.com, 那麼在訪問的時候, 給人的感覺, 是不是好像是我訪問了不同的伺服器, 並且, 他們都是使用預設80埠訪問的.
一. 通過埠區分虛擬主機
1. 將nginx/html文件夾拷貝幾份
[root@localhost nginx]# cp -r html html-8081 [root@localhost nginx]# cp -r html html-8082
接下來, 修改 html-8081, html-8082 下麵的index.html文件
在歡迎的地方, 加上了各自的埠顯示.
2. 修改配置文件
在server節點下麵, 繼續添加兩個server節點, 主要修改其 listen , location.root 這兩個地方
server { listen 8081; server_name localhost; #charset koi8-r; #access_log logs/host.access.log main; location / { root html-8081; index index.html index.htm; } #error_page 404 /404.html; # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } server { listen 8082; server_name localhost; #charset koi8-r; #access_log logs/host.access.log main; location / { root html-8082; index index.html index.htm; } #error_page 404 /404.html; # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } }
3. 刷新配置
[root@localhost sbin]# ./nginx -s reload
4. 查看結果
同一個ip下, 通過不同埠, 確實訪問到了不同的頁面.
二. 通過功能變數名稱來區分
1. 將html再複製幾個
[root@localhost nginx]# cp -r html html-hao123 [root@localhost nginx]# cp -r html html-google
2. 為預設訪問的index.html加一個小尾巴
3. 修改nginx配置文件
server { listen 80; server_name www.hao123.com; #charset koi8-r; #access_log logs/host.access.log main; location / { root html-hao123; index index.html index.htm; } #error_page 404 /404.html; # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } server { listen 80; server_name www.google.com; #charset koi8-r; #access_log logs/host.access.log main; location / { root html-google; index index.html index.htm; } #error_page 404 /404.html; # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } }
4. 刷新配置
[root@localhost sbin]# ./nginx -s reload
5. 修改客戶端的host文件, 將www.baidu.com , www.google.com 映射進去
6. 驗證結果
乍一看, 我訪問的是 hao123 和 google 啊, 怎麼跑到我部署的nginx裡面去了呢. 罒ω罒