1. 程式人生 > >Nginx 簡易教程

Nginx 簡易教程

原文地址:https://www.cnblogs.com/jingmoxukong/p/5945200.html

目錄

Nginx 簡易教程
  概述
  安裝與使用
  nginx 配置實戰
  參考

Nginx 簡易教程

本文是一個 Nginx 極簡教程,目的在於幫助新手快速入門 Nginx。

我在 Github 上建立了一個 Nginx 教程專案: nginx-tutorial

教程中提供了一些常用場景的 Nginx 示例,示例可以通過指令碼一鍵式啟動,方便新手學習。

概述

什麼是 Nginx?

Nginx (engine x)

 是一款輕量級的 Web 伺服器 、反向代理伺服器及電子郵件(IMAP/POP3)代理伺服器。

什麼是反向代理?

反向代理(Reverse Proxy)方式是指以代理伺服器來接受 internet 上的連線請求,然後將請求轉發給內部網路上的伺服器,並將從伺服器上得到的結果返回給 internet 上請求連線的客戶端,此時代理伺服器對外就表現為一個反向代理伺服器。

安裝與使用

安裝

nginx 官網下載地址

釋出版本分為 Linux 和 windows 版本。

也可以下載原始碼,編譯後執行。

從原始碼編譯 Nginx

把原始碼解壓縮之後,在終端裡執行如下命令:

$ ./configure
$ make
$ sudo make install

預設情況下,Nginx 會被安裝在 /usr/local/nginx。通過設定編譯選項,你可以改變這個設定。

Windows 安裝

為了安裝 Nginx / Win32,需先下載它。然後解壓之,然後執行即可。下面以 C 盤根目錄為例說明下:

cd C:
cd C:\nginx-0.8.54   start nginx

Nginx / Win32 是執行在一個控制檯程式,而非 windows 服務方式的。伺服器方式目前還是開發嘗試中。

使用

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 指定你的配置檔案

#執行使用者
#user somebody;

#啟動程序,通常設定成和cpu的數量相等
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檔案,記錄當前啟動的nginx的程序ID pid D:/Tools/nginx-1.10.1/logs/nginx.pid; #工作模式及連線數上限 events { worker_connections 1024; #單個後臺worker process程序的最大併發連結數 } #設定http伺服器,利用它的反向代理功能提供負載均衡支援 http { #設定mime型別(郵件支援型別),型別由mime.types檔案定義 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 指令指定 nginx 是否呼叫 sendfile 函式(zero copy 方式)來輸出檔案,對於普通應用, #必須設為 on,如果用來進行下載等應用磁碟IO重負載應用,可設定為 off,以平衡磁碟與網路I/O處理速度,降低系統的uptime. sendfile on; #tcp_nopush on; #連線超時時間 keepalive_timeout 120; tcp_nodelay on; #gzip壓縮開關 #gzip on; #設定實際的伺服器列表 upstream zp_server1{ server 127.0.0.1:8089; } #HTTP伺服器 server { #監聽80埠,80埠是知名埠號,用於HTTP協議 listen 80; #定義使用www.xx.com訪問 server_name www.helloworld.com; #首頁 index index.html #指向webapp的目錄 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; #反向代理的路徑(和upstream繫結),location 後面設定對映的路徑 location / { proxy_pass http://zp_server1; } #靜態檔案,nginx自己處理 location ~ ^/(images|javascript|js|css|flash|media|static)/ { root D:\01_Workspace\Project\github\zp\SpringNotes\spring-security\spring-shiro\src\main\webapp\views; #過期30天,靜態檔案不怎麼更新,過期可以設大一點,如果頻繁更新,則可以設定得小一點。 expires 30d; } #設定檢視Nginx狀態的地址 location /NginxStatus { stub_status on; access_log on; auth_basic "NginxStatus"; auth_basic_user_file conf/htpasswd; } #禁止訪問 .htxxx 檔案 location ~ /\.ht { deny all; } #錯誤處理頁面(可選擇性配置) #error_page 404 /404.html; #error_page 500 502 503 504 /50x.html; #location = /50x.html { # root html; #} } }

好了,讓我們來試試吧:

  1. 啟動 webapp,注意啟動繫結的埠要和 nginx 中的 upstream 設定的埠保持一致。
  2. 更改 host:在 C:\Windows\System32\drivers\etc 目錄下的 host 檔案中新增一條 DNS 記錄
127.0.0.1 www.helloworld.com
  1. 啟動前文中 startup.bat 的命令
  2. 在瀏覽器中訪問 www.helloworld.com,不出意外,已經可以訪問了。

負載均衡配置

上一個例子中,代理僅僅指向一個伺服器。

但是,網站在實際運營過程中,多半都是有多臺伺服器執行著同樣的 app,這時需要使用負載均衡來分流。

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 {
     #設定mime型別,型別由mime.type檔案定義
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;
    #設定日誌格式 access_log /var/log/nginx/access.log; #設定負載均衡的伺服器列表 upstream load_balance_server { #weigth引數表示權值,權值越高被分配到的機率越大 server 192.168.1.11:80 weight=5; server 192.168.1.12:80 weight=1; server 192.168.1.13:80 weight=6; } #HTTP伺服器 server { #偵聽80埠 listen 80; #定義使用www.xx.com訪問 server_name www.helloworld.com; #對所有請求進行負載均衡請求 location / { root /root; #定義伺服器的預設網站根目錄位置 index index.html index.htm; #定義首頁索引檔案的名稱 proxy_pass http://load_balance_server ;#請求轉向load_balance_server 定義的伺服器列表 #以下是一些反向代理的配置(可選擇性配置) #proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; #後端的Web伺服器可以通過X-Forwarded-For獲取使用者真實IP proxy_set_header X-Forwarded-For $remote_addr; proxy_connect_timeout 90; #nginx跟後端伺服器連線超時時間(代理連線超時) proxy_send_timeout 90; #後端伺服器資料回傳時間(代理髮送超時) proxy_read_timeout 90; #連線成功後,後端伺服器響應時間(代理接收超時) proxy_buffer_size 4k; #設定代理伺服器(nginx)儲存使用者頭資訊的緩衝區大小 proxy_buffers 4 32k; #proxy_buffers緩衝區,網頁平均在32k以下的話,這樣設定 proxy_busy_buffers_size 64k; #高負荷下緩衝大小(proxy_buffers*2) proxy_temp_file_write_size 64k; #設定快取資料夾大小,大於這個值,將從upstream伺服器傳 client_max_body_size 10m; #允許客戶端請求的最大單檔案位元組數 client_body_buffer_size 128k; #緩衝區代理緩衝使用者端請求的最大位元組數 } } }

網站有多個 webapp 的配置

當一個網站功能越來越豐富時,往往需要將一些功能相對獨立的模組剝離出來,獨立維護。這樣的話,通常,會有多個 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 { #此處省略一些基本配置 #預設指向product的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; } } }

https 反向代理配置

一些對安全性要求比較高的站點,可能會使用 HTTPS(一種使用 ssl 通訊標準的安全 HTTP 協議)。

這裡不科普 HTTP 協議和 SSL 標準。但是,使用 nginx 配置 https 需要知道幾點:

  • HTTPS 的固定埠號是 443,不同於 HTTP 的 80 埠
  • SSL 標準需要引入安全證書,所以在 nginx.conf 中你需要指定證書和它對應的 key

其他和 http 反向代理基本一樣,只是在 Server 部分配置有些不同。

  #HTTP伺服器
  server {
      #監聽443埠。443為知名埠號,主要用於HTTPS協議
      listen       443 ssl; #定義使用www.xx.com訪問 server_name www.helloworld.com; #ssl證書檔案位置(常見證書檔案格式為:crt/pem) ssl_certificate cert.pem; #ssl證書key位置 ssl_certificate_key cert.key; #ssl配置引數(選擇性配置) ssl_session_cache shared:SSL:1m; ssl_session_timeout 5m; #數字簽名,此處使用MD5 ssl_ciphers HIGH:!aNULL:!MD5; ssl_prefer_server_ciphers on; location / { root /root; index index.html index.htm; } }

靜態站點配置

有時候,我們需要配置靜態站點(即 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; #轉發任何請求到 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; # windows 伺服器下設定後,依然亂碼,暫時無解 listen 9050 default_server; listen [::]:9050 default_server; server_name _; root /share/fs; }

跨域解決方案

web 領域開發中,經常採用前後端分離模式。這種模式下,前端和後端分別是獨立的 web 應用程式,例如:後端是 Java 程式,前端是 React 或 Vue 應用。

各自獨立的 web app 在互相訪問時,勢必存在跨域問題。解決跨域問題一般有兩種思路:

  1. CORS

在後端伺服器設定 HTTP 響應頭,把你需要執行訪問的域名加入加入 Access-Control-Allow-Origin 中。

  1. jsonp

把後端根據請求,構造 json 資料,並返回,前端用 jsonp 跨域。

這兩種思路,本文不展開討論。

需要說明的是,nginx 根據第一種思路,也提供了一種解決跨域的解決方案。

舉例:www.helloworld.com 網站是由一個前端 app ,一個後端 app 組成的。前端埠號為 9000, 後端埠號為 8080。

前端和後端如果使用 http 進行互動時,請求會被拒絕,因為存在跨域問題。來看看,nginx 是怎麼解決的吧:

首先,在 enable-cors.conf 檔案中設定 cors :

# allow origin list
set $ACAO '*';

# set single origin 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 來引入跨域配置:

# ----------------------------------------------------
# 此檔案為專案 nginx 配置片段
# 可以直接在 nginx config 中 include(推薦)
# 或者 copy 到現有 nginx 中,自行配置
# www.helloworld.com 域名需配合 dns hosts 進行配置 # 其中,api 開啟了 cors,需配合本目錄下另一份配置檔案 # ---------------------------------------------------- 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; } }

到此,就完成了。