Nginx使用upstream實現動靜分離
阿新 • • 發佈:2019-02-13
一、為什麼要進行動靜分離
分離資源,減少不必要到的請求消耗,減少請求延時。
注:我這裡,是nginx處理靜態資源,apache處理動態資源。
場景分析:
1、未分離之前的場景步驟
(1)客戶端請求url到中介軟體(比如nginx,apache)
(2)中介軟體根據url請求相應目錄,程式框架
(3)程式框架執行程式邏輯
(4)程式邏輯請求相應資料資源
(5)將資料資源返回給客戶端
注:其實,靜態資源是不需要經過動態請求,直接中介軟體返回給客戶端就可以了。也就是說只要第1步和第5步就可以了
配置檔案展示:
upstream php_api{ #代理請求到本地apache伺服器,實現動靜分離(這裡我將apache預設埠更改為81) server 127.0.0.1:81; } server { listen 80; server_name www.xiaobudiu.top; access_log /etc/nginx/logs/access/www.xiabudiu.top.access.log main; root /data/www; location ~ \.php$ { #如果網站訪問的url字尾是.php,則代理使用apache進行解析 proxy_pass http://php_api; index index.html index.htm; } #如果請求的是靜態資源,則預設使用nginx進行處理 location ~ \.(jpg|png|gif)$ { expires 1h; gzip on; } location /{ index index.html index.htm; } # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 404 403 /404.html; location = /404.html { root /data/errorPage; } location ~ /\.ht { deny all; } }
或者是這樣:
upstream image { server 192.168.0.3:80; server 192.168.0.4:80; } upstream php { server 192.168.0.5:80; server 192.168.0.6:80; } server { listen 80; server_name www.xiaobudiu.top; access_log /etc/nginx/logs/access/www.xiabudiu.top.access.log main; location /{ #如果uri字尾不是.php或是圖片字尾,就走本地伺服器進行處理 root data/www; index index.php index.html; } location ~* \.php$ { #如果是.php結尾,反向代理到upstream php組裡進行輪詢 proxy_pass http://php; } location ~* "\.(.jpg|png|jpeg|gif)" { #如果是.jpg,.png,.jpeg,.gif結尾,反向代理到upstream image組裡進行輪詢 proxy_pass http://image; } # redirect server error pages to the static page /404.html error_page 500 502 503 504 404 403 /404.html; location = /404.html { root /data/errorPage; } location ~ /\.ht { deny all; } }
注:這是在子配置檔案中進行的定義,比如,上面編輯的就是/etc/nginx/conf.d/www.xiaobudiu.top.conf 檔案
當然,由於nginx對代理有一定要求,所以,在nginx.conf中也要進行一定的定義,比如這樣:
nginx.conf
user nginx; worker_processes 1; worker_rlimit_nofile 65536; error_log /etc/nginx/logs/error/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; multi_accept on; use epoll; } http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /etc/nginx/logs/access/access.log main; sendfile on; #tcp_nopush on; keepalive_timeout 65; client_max_body_size 20m; gzip on; gzip_proxied any; gzip_comp_level 3; gzip_min_length 1k; gzip_buffers 16 32k; gzip_http_version 1.0; gzip_types text/plain text/css application/json application/xml+rss text/javascript image/jpeg image/gif image/png; fastcgi_buffers 256 16k; fastcgi_buffer_size 128k; fastcgi_connect_timeout 3s; fastcgi_send_timeout 120s; fastcgi_read_timeout 120s; reset_timedout_connection on; server_names_hash_bucket_size 100; include /etc/nginx/conf.d/*.conf; }
最後,需要說明的是,上述配置檔案只是為了說明反向代理和負載均衡是如何實現的,並沒有結合實際專案。
注:負載均衡中多型伺服器間的資料同步這裡採用rsync,當然,還有其他方式。可參考: