在電腦網路中,反向 Proxy是Proxy 伺服器的一種。它根據用戶端的請求,從後端的伺服器上擷取資源,然後再將這些資源返回給用戶端。與前向代理不同,前向代理作為一個媒介將互連網上擷取的資源返回給相關聯的用戶端,而反向 Proxy是在伺服器端作為代理使用,而不是用戶端。
Nginx(發音同engine x)是一個網頁伺服器,它能反向 ProxyHTTP, HTTPS, SMTP, POP3, IMAP的協議連結,以及一個負載平衡器和一個HTTP緩衝。
起初是供俄國大型的門戶網站及搜尋引擎Rambler(俄語:Рамблер)使用。此軟體BSD-like協議下發行,可以在UNIX、GNU/Linux、BSD、Mac OS X、Solaris,以及Microsoft Windows等作業系統中運行。
下載地址:http://nginx.org/en/download.html
下載完成後解壓到任意目錄,雙擊nginx.exe啟動
開啟localhost啟動成功了
開啟nginx的主設定檔conf/nginx.conf
server { listen 80; server_name localhost; #charset koi8-r;#access_log logs/host.access.log main; location / { root html; indexindex.html index.htm; } #error_page 404 /404.html;# redirect server error pages to the static page /50x.html# error_page 500502503504 /50x.html; location = /50x.html { root html; } # proxy the PHP scripts to Apache listening on 127.0.0.1:80##location ~ \.php$ {# proxy_pass http://127.0.0.1;#}# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000##location ~ \.php$ {# root html;# fastcgi_pass 127.0.0.1:9000;# fastcgi_index index.php;# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;# include fastcgi_params;#}# deny access to .htaccess files, if Apache's document root# concurs with nginx's one##location ~ /\.ht {# deny all;#} }
listen:表示當前的Proxy 伺服器監聽的連接埠,預設的是監聽80連接埠。注意,如果我們配置了多個server,這個listen要配置不一樣,不然就不能確定轉到哪裡去了。
server_name:表示監聽到之後需要轉到哪裡去,這時我們直接轉到本地,這時是直接到nginx檔案夾內。
location:表示匹配的路徑,這時配置了/表示所有請求都被匹配到這裡
root:裡面配置了root這時表示當匹配這個請求的路徑時,將會在這個檔案夾內尋找相應的檔案,這裡對我們之後的靜態檔案伺服很有用。
index:當沒有指定首頁時,預設會選擇這個指定的檔案,它可以有多個,並按順序來載入,如果第一個不存在,則找第二個,依此類推。
下面的error_page是代表錯誤的頁面,這裡我們暫時不用,先不管它。
轉寄到tomcat需要修改兩個地方
server_name localhost:8080; location / { proxy_pass http://localhost:8080; }
我們就修改了上面兩個地方,我的tomcat在8080連接埠,可以根據自己的需要修改。這裡有一個新元素proxy_pass,它表示代理路徑,相當於轉寄,而不像之前說的root必須指定一個檔案夾。
此時我們修改了檔案,是不是就意思著必須先關了nginx再重新啟動了,其實不必,nginx可以重新負載檔案的。
nginx -s reload
nginx除了啟動其它命令都要在命令列下運行
開啟localhost已經代理到tomcat
負載平衡配置
upstream local_tomcat { server localhost:8080; server localhost:9080; } server { listen 80; server_name localhost; #直接匹配網站根,通過網域名稱訪問網站首頁比較頻繁,使用這個會加速處理,官網如是說。#這裡是直接轉寄給後端應用伺服器了,也可以是一個靜態首頁# 第一個必選規則 location = / { proxy_pass http://local_tomcat/index } # 第二個必選規則是處理靜態檔案請求,這是nginx作為http伺服器的強項# 有兩種配置模式,目錄匹配或尾碼匹配,任選其一或搭配使用 location ^~ /static/ { root /webroot/static/; expires 24h; } location ~* \.(gif|jpg|jpeg|png|css|js|ico)$ { root /webroot/res/; expires 30d; } #第三個規則就是通用規則,用來轉寄動態請求到後端應用伺服器#非靜態檔案請求就預設是動態請求,自己根據實際把握#畢竟目前的一些架構的流行,帶.php,.jsp尾碼的情況很少了 location / { proxy_pass http://local_tomcat } }
關閉nginx : nginx -s stop
參考:http://nginx.org/en/docs/windows.html
http://cxshun.iteye.com/blog/1535188
').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($('
').text(i)); }; $numbering.fadeIn(1700); }); });
以上就介紹了nginx反向 Proxytomcat實現負載平衡,包括了方面的內容,希望對PHP教程有興趣的朋友有所協助。