前提:最近在研究nginx的用法,在windows上小試了一下,因爲windows下不支持nginx緩存配置,因此本文主要是講nginx,以及反向代理與負載均衡。javascript
【1、爲何要使用nginx】css
要回答爲何要使用nginx,那就先說說nginx能作些什麼。html
首先,nginx能作反向代理,那麼什麼是反向代理呢,舉個栗子,我想在本地使用 www.mickey.com 的域名去訪問 www.taobao.com。那麼這個時候咱們就能夠經過nginx去實現。java
再者,nginx能實現負載均衡,什麼是負載均衡呢?就是個人項目部署在不一樣的服務器上,可是經過統一的域名進入,nginx則對請求進行分發,減輕了服務器的壓力。node
在上面這兩種狀況下,nginx服務器的做用都只是做爲分發服務器,真正的內容,咱們能夠放在其餘的服務器上,這樣來,還能起到一層安全隔壁的做用,nginx做爲隔離層。linux
其次,nginx還能解決跨域的問題。nginx
【2、、nginx安裝】web
在 http://nginx.org/ 下載對應版本的nginxnpm
在 nginx 的目錄下使用 start nginx 或者 雙擊 nginx.exe 打開nginxwindows
【3、nginx配置屬性說明】
#全局設置
-1/var/log/nginx//var/run/nginx.pid;/O Multiplexing)中的一種方式,可是僅用於linux2.6以上內核,能夠大大提升nginx的性能 worker_connections 1024/etc/nginx/mime.types; default_type application/octet-stream;/var/log/nginx//O處理速度,下降系統的uptime.65"MSIE [1-6]\.(?!.*SV1)"4/etc/nginx/conf.d/*/etc/nginx/sites-enabled/*192.168.8.1:3128 weight=5192.168.8.2:80 weight=1192.168.8.3:80 weight=680/www.xx.com.access.log main;//root; #定義服務器的默認網站根目錄位置/$fastcgi_script_name; include /etc/nginx/fastcgi_params;500 502 503 504 /50x.html; location = /50x.html { root /root;~ ^/(p_w_picpaths|javascript|js|css|flash|media|static)//var/www/virtual/~/root; fastcgi_pass 127.0.0.1:9000/home/www/www$fastcgi_script_name;/NginxStatus {"NginxStatus"/htpasswd;~ /\.ht {168.880192.168.8~ .*/root;#定義服務器的默認網站根目錄位置-Forwarded--Real--Forwarded-9090904*2
【4、nginx反向代理】
本地起兩個項目,源碼在此。
分別在這兩個文件夾下面運行
npm install node server.js
在瀏覽器輸入
本機ip:4789
本機ip:5789
能夠訪問到這兩個頁面
接着咱們想使用
test.nginx.com訪問到 頁面5789
test.nginx.com/bug 訪問到頁面5789
則咱們首先須要配置hosts
win 下hosts 的地址爲 C:\Windows\System32\drivers\etc
咱們須要在hosts文件裏面添加以下配置
172.18.144.23 test.nginx.com
而後在 nginx 的 http 模塊上添加一個 server
server { listen 80; server_name test.nginx.com; location / { proxy_pass http://172.18.144.23:4789/; } location /buy { proxy_pass http://172.18.144.23:5789/; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } }
而後重啓nginx
在瀏覽器輸入 test.nginx.com
在瀏覽器輸入 test.nginx.com/bug
反向代理就這樣子啦。
【5、nginx負載均衡】
在nginx中配置http
首先配置負載均衡的服務
在http模塊中添加以下配置
upstream webservers { server 172.18.144.23:4789 weight=10; server 172.18.144.23:5789 weight=10; }
把server改成
server { listen 80; server_name test.nginx.com; location / { proxy_pass http://webservers; } location /buy { proxy_pass http://172.18.144.23:5789/; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } }
在瀏覽器輸入 test.nginx.com,刷新,咱們能夠看到兩種頁面,說明nginx已經把咱們的請求分發到不一樣的地方去了。
A