使用 Nginx 作為反向代理伺服器 (Reverse Proxy)


  1. 說明
    1. nginx.conf
    2. 心得
  2. 參考資料

說明如何使用 Nginx for Windows 作為反向代理伺服器。

logo

說明

Nginx 分為 Open Source 以及需要付費,有著更為完善功能及有支援服務的 Nginx Plus

目前 Nginx 是屬於 F5 公司的解決方案與產品,而開源版本則可以從 https://nginx.org/en/ 下載,或從 Nginx 於 GitHub 所提供的 Release Repos 進行下載。

本次的測試環境使用 Nginx Open Source 1.23.2,並且在 Windows Server 2019 上進行測試。


下載後解壓縮就可以使用,藉由執行 nginx.exe 啟動執行。

設定上則是藉由調整 nginx.conf,執行 nginx 後,如果有互動的需求可以藉由 cmd 透過 nginx.exe 使用參數進行控制

nginx -s stop
nginx -s quit

rem Reload  nginx.conf
nginx -s reload
rem Reopen Log files
nginx -s reopen

nginx.conf

/conf/nginx.conf

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;

events {
    worker_connections  1024;
}


http {
    include       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  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       8080;
        server_name  sdwh.dev;

        #charset koi8-r;
        #access_log  logs/host.access.log  main;

        location / {
            proxy_pass https://sdwh.dev/;
        }
    }

    server {
        listen       80;
        server_name  hostname;

        #charset koi8-r;
        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }

        location /www {
            proxy_pass http://192.168.112.152:8080/;
        }
        location /tour {
            proxy_pass https://tour.sdwh.dev/;
            sub_filter '/assets/'  '/tour/assets/';
            sub_filter 'assets/'  '/tour/assets/';
            sub_filter_once off;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

在 conf 的設定當中,server 用於設定要監聽的 port,搭配 location 由子目錄判斷回應的內容。

而要進行反向代理,就是設定 proxy_pass 的位址,但在回應上可能會有代理錯誤 (可能被各種原因阻擋),因此仍是有相關的問題要去克服。

而縱使成功進行反向代理,相關的資源檔案可能因為網頁本身的絕對路徑或者相對路徑無法成功載入,這個時候可以利用多個 location 或者是使用 sub_filter 的方式將回應內容強制取代,當然,這會是一個不斷測試的手工過程 😅

心得

Nginx 的 conf 設定直觀易懂,並且有第三方套件可以擴充功能。然而在一些討論中有看到 Nginx 在 Windows 環境穩定度仍有提升的空間,此外由於有 Nginx Plus 的選項,在正式營運環境,如果採用 Nginx 應仍會以 Nginx Plus 作為選擇。Open Source 的 Nginx 較為適合作為 POC 或者個人用途的反向代理伺服器工具 😃

參考資料

KingKong Bruce記事 - NGINX 基礎入門(WINDOWS 版)

App-Scope - Nginx 學習筆記