天天都在用的 Nginx,可你知道如何用一個反向代理實現多個不同類型的後端網站訪問嗎?

  • 2019 年 12 月 17 日
  • 筆記

前段時間公司根據要求需要將聚石塔上伺服器從杭州整體遷移到張家口,剛好趁這次機會將這些亂七八糟的伺服器做一次梳理和整合。斷斷續續一個月遷移完成大概優化掉了 1/3 的機器,完成之後遇到了一些問題,比如:曾經零零散散部署在生產上一些可視化 UI:ApolloKibanaGrafanaJenkins 等等服務,這些服務都採用了 80 或者其它公網埠進行對外暴露。

為了安全,現在不再開放非 80 之外的公網埠。由於機器少了,80 埠不夠,這些可視化 UI 不再能直接訪問到了。所以需另尋其他出路。

用 Nginx 做反向代理

為了解決這兩個問題,自然第一反應想到的就是使用反向代理,我的理想構思下應該是下圖這樣的。

既用戶所有的請求都經過 Nginx,讓 Nginx 來判斷當前 URL 需要跳轉到哪一個後端代理上。比較好的策略應該是讓 Nginx 來判斷當前的 Host 是什麼來決定跳轉到哪一個後端的 Webserver 上,比如: a.mip.com 就跳轉到 Apolloj.mip.com 就跳轉到 Jenkins。以此類推,這樣就可以完美解決了。

一個完整的演示實例

為了實現上面的需求,在 Nginx 中你完全可以使用 Rewrite 模組下 if 指令來完成。由於 Nginx 默認帶的模組比較少,如果需使用第三方模組,你可能還需要重新編譯 Nginx。所以這裡直接使用 OpenResty,它擴展了 Nginx,並且集成了很多成熟的 LUA 模組。可自行下載最新的 1.15.8 版本,其安裝方式和 Nginx 一模一樣。

項目地址:https://openresty.org/en/download.html

OpenResty 默認是安裝到 /usr/local/ 目錄下,當你看到有一個 openresty 目錄就表示你安裝成功。

[root@localhost local]# ls  bin  etc  games  include  lib  lib64  libexec  openresty  sbin  share  src  [root@localhost local]# pwd  /usr/local

接下來你可以使用 nginx -v 來驗證下 OpenResty 版本號。

[root@localhost sbin]# pwd  /usr/local/openresty/nginx/sbin  [root@localhost sbin]#  [root@localhost sbin]# ./nginx -v  nginx version: openresty/1.15.8.1

為了演示方便,我就直接使用 Nginx 開啟三個 Server。

192.168.23.129:80      # 在 80 埠上開啟第一個網站,就是 Proxy 了。  192.168.23.129:8001     # 在 8001 埠上開啟第二個網站,模擬 Apollo。  192.168.23.129:8002     # 在 8002 埠上開啟第三個網站,模擬 Jenkins。

首先,我們在 Nginx 中的配置好三個網站。

  1. Apollo 配置片斷
server {          listen       8001;          server_name  somename  alias  another.alias;          location / {              root   html;              index  apollo.html;          }  }

8001 埠網站的默認頁是 apollo.html,這個 apollo.html 所在路徑就是在 Nginx 目錄下的 html 目錄,如下所示。

[root@localhost html]# pwd  /usr/local/openresty/nginx/html  [root@localhost html]# ls  50x.html  apollo.html  index.html  jenkins.html
  1. Jenkins 配置片斷

Jenkins.html 的文件所在路徑如下所示,不再贅述。

server {          listen       8002;          server_name  somename  alias  another.alias;          location / {              root   html;              index  jenkins.html;          }  }
  1. Proxy 配置片斷

我們可以看到,這裡只需要使用 Rewrite 模組下的 if 條件語句。然後通過 $host 系統變數判斷當前的 URL 中的 host 的值來實現跳轉到相應的網站。

server {          listen       80;          server_name  localhost;            location / {               if ($host = "a.mip.com") {                 proxy_pass http://localhost:8001;             }               if ($host = "j.mip.com") {                 proxy_pass http://localhost:8002;             }  }

其次,我們做好對應域名關係映射。這裡為了演示方便,我們直接在 hosts 文件中進行配置。

$ cat /etc/hosts  192.168.23.129 a.mip.com  192.168.23.129 j.mip.com

最後,啟動 Nginx。

[root@localhost sbin]# ./nginx  [root@localhost sbin]#  [root@localhost sbin]#  [root@localhost sbin]# netstat -tlnp  Active Internet connections (only servers)  Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name  tcp        0      0 0.0.0.0:8001            0.0.0.0:*               LISTEN      3802/nginx: master  tcp        0      0 0.0.0.0:8002            0.0.0.0:*               LISTEN      3802/nginx: master  tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      3802/nginx: master  tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1172/sshd  tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN      1724/master  tcp6       0      0 :::22                   :::*                    LISTEN      1172/sshd  tcp6       0      0 ::1:25                  :::*                    LISTEN      1724/master

通過上面輸出看到,8080018002 埠都已經開啟了,接下來大家可以到瀏覽器去驗證一下了。

從上圖中,我們可以看到通過不同域名成功的訪問到了不同的後端應用。以下是全部的 Nginx 配置文件:

$ cat 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  '$host ----> $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       80;          server_name  localhost;            #charset koi8-r;            #access_log  logs/host.access.log  main;        # location = /get {          #     set_unescape_uri $key $arg_key;  # this requires ngx_set_misc          #     redis2_query get $key;          #     redis2_pass 10.105.13.174:6379;          # }            location / {               if ($host = "a.mip.com") {                 proxy_pass http://localhost:8001;             }               if ($host = "j.mip.com") {                 proxy_pass http://localhost:8002;             }               root   html;             index  index.html index.htm;            }            #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;          }            # proxy the PHP scripts to Apache listening on 127.0.0.1:80          #          #location ~ .php$ {          #    proxy_pass   http://127.0.0.1;          #}            # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000          #          #location ~ .php$ {          #    root           html;          #    fastcgi_pass   127.0.0.1:9000;          #    fastcgi_index  index.php;          #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;          #    include        fastcgi_params;          #}            # deny access to .htaccess files, if Apache's document root          # concurs with nginx's one          #          #location ~ /.ht {          #    deny  all;          #}      }          # another virtual host using mix of IP-, name-, and port-based configuration      #      server {          listen       8001;          server_name  somename  alias  another.alias;          location / {              root   html;              index  apollo.html;          }      }        server {          listen       8002;          server_name  somename  alias  another.alias;          location / {              root   html;              index  jenkins.html;          }      }        # HTTPS server      #      #server {      #    listen       443 ssl;      #    server_name  localhost;        #    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   html;      #        index  index.html index.htm;      #    }      #}    }

至此,我們就演示完了一個反向代理實現多個不同類型的後端網站訪問的場景,希望本篇文章對你有所幫助!

來源:部落格園 原文:https://url.cn/5iSfcUN 題圖:來自Google圖片搜索 版權:本文版權歸原作者所有 投稿:歡迎投稿,郵箱: [email protected]