1.反向代理實例一
實現效果:使用nginx反向代理,訪問www.123.com直接跳轉到122.51.50.249:8080
1.1.實驗代碼
1)啓動一個 tomcat,瀏覽器地址欄輸入 122.51.50.249:8080,出現如下界面
2)通過修改本地 host文件,將 www.123.com映射到 122.51.50.249
配置完成之後,我們便可以通過 www.123.com:8080訪問到第一步出現的 Tomcat初始界
面。那麼如何只需要輸入 www.123.com便可以跳轉到 Tomcat初始界面呢?
便用到 nginx的反向代理。
server {
listen 80;
server_name www.123.com;
location / {
#root html;
proxy_pass http://122.51.50.249:8080;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
重新啓動nginx:
如上配置,我們監聽80端口,訪問域名爲www.123.com,不加端口號時默認爲80端口,故訪問該域名時會跳轉到122.51.50.249:8080路徑上。在瀏覽器端輸入www.123.com結果如下:
2.反向代理實例二
實現效果:使用nginx反向代理,根據訪問的路徑跳轉到不同端口的服務中
nginx監聽端口爲9001,
訪問 http://122.51.50.249:9001/edu/直接跳轉到122.51.50.249:8080
訪問 http://122.51.50.249:9001/vod/直接跳轉到122.51.50.249:8090
2.1.實驗代碼
第一步,準備兩個tomcat,一個8080端口,一個8090端口,並準備好測試的頁面
第二步,修改nginx的配置文件
在http塊中添加server{}
server {
listen 9001;
server_name www.123.com;
location ~ /edu/ {
#root html;
proxy_pass http://122.51.50.249:8080;
index index.html index.htm;
}
location ~ /vod/ {
#root html;
proxy_pass http://122.51.50.249:8090;
index index.html index.htm;
}
}
Location匹配規則
模式 | 含義 |
---|---|
location = /uri | = 用於不含正則表達式的 uri 前,要求請求字符串與 uri 嚴格匹配,如果匹配成功,就停止繼續向下搜索並立即處理該請求 |
location ^~ /uri | ^~ 開頭對URL路徑進行前綴匹配,並且在正則之前。 |
location ~ pattern | 用於表示 uri 包含正則表達式,並且區分大小寫。 |
location ~* pattern | 用於表示 uri 包含正則表達式,並且不區分大小寫。 |
location / | 通用匹配,任何未匹配到其它location的請求都會匹配到,相當於switch中的defaut |
注意:如果 uri 包含正則表達式,則必須要有 ~ 或者 ~* 標識
測試訪問