點擊上方「後端技術精選」,選擇「置頂公眾號」
技術文章第一時間送達!
作者:dunwu
github.com/dunwu/nginx-tutorial
推薦閱讀(點擊即可跳轉閱讀)
1. SpringBoot內容聚合
2. 面試題內容聚合
3. 設計模式內容聚合
4. 排序算法內容聚合
5. 多線程內容聚合
Nginx 極簡教程本項目是一個 Nginx 極簡教程,目的在於幫助新手快速入門 Nginx。
示例Demo:
https://github.com/dunwu/nginx-tutorial/tree/master/demos
Demo目錄中的示例模擬了工作中的一些常用實戰場景,並且都可以通過腳本一鍵式啟動,讓您可以快速看到演示效果。
簡介什麼是 Nginx?
Nginx (engine x) 是一款輕量級的 Web 伺服器 、反向代理伺服器及電子郵件(IMAP/POP3)代理伺服器。
什麼是反向代理?
反向代理(Reverse Proxy)方式是指以代理伺服器來接受 internet 上的連接請求,然後將請求轉發給內部網絡上的伺服器,並將從伺服器上得到的結果返回給 internet 上請求連接的客戶端,此時代理伺服器對外就表現為一個反向代理伺服器。
詳細安裝方法請參考:
https://github.com/dunwu/nginx-tutorial/blob/master/install-nginx.md
nginx 的使用比較簡單,就是幾條命令。
常用到的命令如下:
nginx -s stop 快速關閉Nginx,可能不保存相關信息,並迅速終止web服務。
nginx -s quit 平穩關閉Nginx,保存相關信息,有安排的結束web服務。
nginx -s reload 因改變了Nginx相關配置,需要重新加載配置而重載。
nginx -s reopen 重新打開日誌文件。
nginx -c filename 為 Nginx 指定一個配置文件,來代替預設的。
nginx -t 不運行,僅僅測試配置文件。nginx 將檢查配置文件的語法的正確性,並嘗試打開配置文件中所引用到的文件。
nginx -v 顯示 nginx 的版本。
nginx -V 顯示 nginx 的版本,編譯器版本和配置參數。
如果不想每次都敲命令,可以在 nginx 安裝目錄下新添一個啟動批處理文件startup.bat,雙擊即可運行。內容如下:
@echo off
rem 如果啟動前已經啟動nginx並記錄下pid文件,會kill指定進程
nginx.exe -s stop
rem 測試配置文件語法正確性
nginx.exe -t -c conf/nginx.conf
rem 顯示版本信息
nginx.exe -v
rem 按照指定配置去啟動nginx
nginx.exe -c conf/nginx.conf
如果是運行在 Linux 下,寫一個 shell 腳本,大同小異。
Nginx 實戰我始終認為,各種開發工具的配置還是結合實戰來講述,會讓人更易理解。
Http 反向代理我們先實現一個小目標:不考慮複雜的配置,僅僅是完成一個 http 反向代理。
nginx.conf 配置文件如下:
註:conf/nginx.conf 是 nginx 的默認配置文件。你也可以使用 nginx -c 指定你的配置文件
worker_processes 1;
error_log D:/Tools/nginx-1.10.1/logs/error.log;
error_log D:/Tools/nginx-1.10.1/logs/notice.log notice;
error_log D:/Tools/nginx-1.10.1/logs/info.log info;
pid D:/Tools/nginx-1.10.1/logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include D:/Tools/nginx-1.10.1/conf/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 D:/Tools/nginx-1.10.1/logs/access.log main;
rewrite_log on;
sendfile on;
keepalive_timeout 120;
tcp_nodelay on;
upstream zp_server1{
server 127.0.0.1:8089;
}
server {
listen 80;
server_name www.helloworld.com;
index index.html
root D:\01_Workspace\Project\github\zp\SpringNotes\spring-security\spring-shiro\src\main\webapp;
charset utf-8;
proxy_connect_timeout 180;
proxy_send_timeout 180;
proxy_read_timeout 180;
proxy_set_header Host $host;
proxy_set_header X-Forwarder-For $remote_addr;
location / {
proxy_pass http://zp_server1;
}
location ~ ^/(images|javascript|js|css|flash|media|static)/ {
root D:\01_Workspace\Project\github\zp\SpringNotes\spring-security\spring-shiro\src\main\webapp\views;
expires 30d;
}
location /NginxStatus {
stub_status on;
access_log on;
auth_basic "NginxStatus";
auth_basic_user_file conf/htpasswd;
}
location ~ /\.ht {
deny all;
}
}
}
好了,讓我們來試試吧:
啟動 webapp,注意啟動綁定的埠要和 nginx 中的 upstream 設置的埠保持一致。
更改 host:在 C:\Windows\System32\drivers\etc 目錄下的 host 文件中添加一條 DNS 記錄127.0.0.1 www.helloworld.com
啟動前文中 startup.bat 的命令
在瀏覽器中訪問 www.helloworld.com,不出意外,已經可以訪問了。
Https 反向代理一些對安全性要求比較高的站點,可能會使用 HTTPS(一種使用 ssl 通信標準的安全 HTTP 協議)。
這裡不科普 HTTP 協議和 SSL 標準。但是,使用 nginx 配置 https 需要知道幾點:
其他和 http 反向代理基本一樣,只是在 Server 部分配置有些不同。
server {
listen 443 ssl;
server_name www.helloworld.com;
ssl_certificate cert.pem;
ssl_certificate_key cert.key;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
location / {
root /root;
index index.html index.htm;
}
}
前面的例子中,代理僅僅指向一個伺服器。
但是,網站在實際運營過程中,大部分都是以集群的方式運行,這時需要使用負載均衡來分流。nginx 也可以實現簡單的負載均衡功能。
假設這樣一個應用場景:將應用部署在 192.168.1.11:80、192.168.1.12:80、192.168.1.13:80 三臺 linux 環境的伺服器上。網站域名叫 www.helloworld.com,公網 IP 為 192.168.1.11。在公網 IP 所在的伺服器上部署 nginx,對所有請求做負載均衡處理(下面例子中使用的是加權輪詢策略)。
nginx.conf 配置如下:
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
access_log /var/log/nginx/access.log;
upstream load_balance_server {
server 192.168.1.11:80 weight=5;
server 192.168.1.12:80 weight=1;
server 192.168.1.13:80 weight=6;
}
server {
listen 80;
server_name www.helloworld.com;
location / {
root /root;
index index.html index.htm;
proxy_pass http://load_balance_server ;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_connect_timeout 90;
proxy_send_timeout 90;
proxy_read_timeout 90;
proxy_buffer_size 4k;
proxy_buffers 4 32k;
proxy_busy_buffers_size 64k;
proxy_temp_file_write_size 64k;
client_max_body_size 10m;
client_body_buffer_size 128k;
}
}
}
Nginx 提供了多種負載均衡策略,讓我們來一一了解一下:
負載均衡策略在各種分布式系統中基本上原理一致,對於原理有興趣,不妨參考:
https://dunwu.github.io/javaweb/#/theory/load-balance
輪詢upstream bck_testing_01 {
server 192.168.250.220:8080
server 192.168.250.221:8080
server 192.168.250.222:8080
}
upstream bck_testing_01 {
server 192.168.250.220:8080 weight=3
server 192.168.250.221:8080
server 192.168.250.222:8080
}
upstream bck_testing_01 {
least_conn;
server 192.168.250.220:8080
server 192.168.250.221:8080
server 192.168.250.222:8080
}
upstream bck_testing_01 {
least_conn;
server 192.168.250.220:8080 weight=3
server 192.168.250.221:8080
server 192.168.250.222:8080
}
upstream bck_testing_01 {
ip_hash;
server 192.168.250.220:8080
server 192.168.250.221:8080
server 192.168.250.222:8080
}
upstream bck_testing_01 {
hash $request_uri;
server 192.168.250.220:8080
server 192.168.250.221:8080
server 192.168.250.222:8080
}
當一個網站功能越來越豐富時,往往需要將一些功能相對獨立的模塊剝離出來,獨立維護。這樣的話,通常,會有多個 webapp。
舉個例子:假如 www.helloworld.com 站點有好幾個 webapp,finance(金融)、product(產品)、admin(用戶中心)。訪問這些應用的方式通過上下文(context)來進行區分:
www.helloworld.com/finance/
www.helloworld.com/product/
www.helloworld.com/admin/
我們知道,http 的默認埠號是 80,如果在一臺伺服器上同時啟動這 3 個 webapp 應用,都用 80 埠,肯定是不成的。所以,這三個應用需要分別綁定不同的埠號。
那麼,問題來了,用戶在實際訪問 www.helloworld.com 站點時,訪問不同 webapp,總不會還帶著對應的埠號去訪問吧。所以,你再次需要用到反向代理來做處理。
配置也不難,來看看怎麼做吧:
http {
upstream product_server{
server www.helloworld.com:8081;
}
upstream admin_server{
server www.helloworld.com:8082;
}
upstream finance_server{
server www.helloworld.com:8083;
}
server {
location / {
proxy_pass http://product_server;
}
location /product/{
proxy_pass http://product_server;
}
location /admin/ {
proxy_pass http://admin_server;
}
location /finance/ {
proxy_pass http://finance_server;
}
}
}
有時候,我們需要配置靜態站點(即 html 文件和一堆靜態資源)。
舉例來說:如果所有的靜態資源都放在了 /app/dist 目錄下,我們只需要在 nginx.conf 中指定首頁以及這個站點的 host 即可。
配置如下:
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
gzip on;
gzip_types text/plain application/x-javascript text/css application/xml text/javascript application/javascript image/jpeg image/gif image/png;
gzip_vary on;
server {
listen 80;
server_name static.zp.cn;
location / {
root /app/dist;
index index.html;
}
}
}
然後,添加 HOST:
127.0.0.1 static.zp.cn
此時,在本地瀏覽器訪問 static.zp.cn ,就可以訪問靜態站點了。
搭建文件伺服器有時候,團隊需要歸檔一些數據或資料,那麼文件伺服器必不可少。使用 Nginx 可以非常快速便捷的搭建一個簡易的文件服務。
Nginx 中的配置要點:
將 autoindex 開啟可以顯示目錄,默認不開啟。
將 autoindex_exact_size 開啟可以顯示文件的大小。
將 autoindex_localtime 開啟可以顯示文件的修改時間。
root 用來設置開放為文件服務的根路徑。
charset 設置為 charset utf-8,gbk;,可以避免中文亂碼問題(windows 伺服器下設置後,依然亂碼,本人暫時沒有找到解決方法)。
一個最簡化的配置如下:
autoindex on;
autoindex_exact_size on;
autoindex_localtime on;
server {
charset utf-8,gbk;
listen 9050 default_server;
listen [::]:9050 default_server;
server_name _;
root /share/fs;
}
web 領域開發中,經常採用前後端分離模式。這種模式下,前端和後端分別是獨立的 web 應用程式,例如:後端是 Java 程序,前端是 React 或 Vue 應用。
各自獨立的 web app 在互相訪問時,勢必存在跨域問題。解決跨域問題一般有兩種思路:
CORS
在後端伺服器設置 HTTP 響應頭,把你需要允許訪問的域名加入 Access-Control-Allow-Origin 中。
jsonp
把後端根據請求,構造 json 數據,並返回,前端用 jsonp 跨域。
這兩種思路,本文不展開討論。
需要說明的是,nginx 根據第一種思路,也提供了一種解決跨域的解決方案。
舉例:www.helloworld.com 網站是由一個前端 app ,一個後端 app 組成的。前端埠號為 9000, 後端埠號為 8080。
前端和後端如果使用 http 進行交互時,請求會被拒絕,因為存在跨域問題。來看看,nginx 是怎麼解決的吧:
首先,在 enable-cors.conf 文件中設置 cors :
set $ACAO '*';
if ($http_origin ~* (www.helloworld.com)$) {
set $ACAO $http_origin;
}
if ($cors = "trueget") {
add_header 'Access-Control-Allow-Origin' "$http_origin";
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}
if ($request_method = 'OPTIONS') {
set $cors "${cors}options";
}
if ($request_method = 'GET') {
set $cors "${cors}get";
}
if ($request_method = 'POST') {
set $cors "${cors}post";
}
接下來,在你的伺服器中 include enable-cors.conf 來引入跨域配置:
upstream front_server{
server www.helloworld.com:9000;
}
upstream api_server{
server www.helloworld.com:8080;
}
server {
listen 80;
server_name www.helloworld.com;
location ~ ^/api/ {
include enable-cors.conf;
proxy_pass http://api_server;
rewrite "^/api/(.*)$" /$1 break;
}
location ~ ^/ {
proxy_pass http://front_server;
}
}
到此,就完成了。
參考http://tool.oschina.net/apidocs/apidoc?api=nginx-zh
http://tengine.taobao.org/book/index.html
https://github.com/trimstray/nginx-admins-handbook
https://nginxconfig.io/
看到這裡了,關注一個?