nginx 的sub_filter

需求/問題

最近在作一個需求, 大概的部署模型是這樣的:html

因爲有嚴格的端口限制(對外暴露80端口) 因此咱們在右邊的服務器纔有一個nginx來根據api path作反向代理.java

由於想把咱們的代碼跟CI jenkins集成, 因此想找個辦法來看看怎麼將jenkins也經過代理服務器的80端口訪問?nginx

步驟

step1:

咱們將/j/的路徑訪問到jenkins服務器地址.  好比服務器爲: test.com, 那麼咱們經過test.com/j/來訪問jenkins:chrome

location /j/ {
      proxy_pass http://127.0.0.1:8002/; #這裏的
      rewrite ^/j/(.*)$ /$1 break;   # 而且重寫去掉/j 而後發給jenkins
    }         後端

問題:  發現自動重定向了到test.com/login:api

Step2:

添加sub_filter來重寫content:服務器

location /j/ {
      proxy_pass http://127.0.0.1:8002/; #這裏的端口記得改爲項目對應的哦
      proxy_set_header Accept-Encoding "";
       rewrite ^/j/(.*)$ /$1 break;
      sub_filter '/login' '/j/login';
      sub_filter '/static/' '/j/static/';
      sub_filter_types *;
      sub_filter_once off;
      sub_filter '/adjuncts' '/j/adjuncts';
    }       工具

 這裏面看到我加了不少的聲明. 爲了方便我來解釋下:ui

sub_filter '/login' '/j/login';   --- 這個咱們發現返回值裏面有重定向 因此咱們須要把jenkins返回的內容進行替換重寫. sub_filter       sub_filter '/adjuncts' '/j/adjuncts';  -- 這個也是相似.  可是的多用firefox/chrome的開發者工具纔看得出來 有哪些返回失敗.spa

注意只有在新版本nginx中才支持多sub_filter.

sub_filter_types *;  -- 對全部請求響應類型都作sub_filter指定的替換.

sub_filter_once off; -- sub_filter會執行屢次而不是一次. 效果相似於java中的string.replaceAll而不是replace.

proxy_set_header Accept-Encoding "";  -- 設置這個得緣由是告訴後端不要進行gzip壓縮.  若是是gzip壓縮流, 那麼咱們就無法進行替換了.

# 貼一個完整的nginx.conf

        server_name test.com localhost;
        index index.html;

        root  /usr/share/nginx/ui;

        # 避免訪問出現 404 錯誤

        location /api/ {
          proxy_pass http://test.com:8000; #這裏的端口記得改爲項目對應的哦
          proxy_set_header X-Forwarded-Proto $scheme;
          proxy_set_header X-Forwarded-Port $server_port;
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
          proxy_set_header Upgrade $http_upgrade;
          proxy_set_header Connection "upgrade";
        }
        location /j/ {
          gzip off;
          proxy_pass http://127.0.0.1:8002/; #這裏的端口記得改爲項目對應的哦
          proxy_set_header Accept-Encoding "";
          rewrite ^/j/(.*)$ /$1 break;
          sub_filter '/login' '/j/login';
          sub_filter '/static/' '/j/static/';
          sub_filter_types *;
          sub_filter_once off;
          sub_filter '/adjuncts' '/j/adjuncts';
        }
         location /chatbot/ {
          proxy_pass http://test.com:8001; #這裏的端口記得改爲項目對應的哦
          proxy_set_header X-Forwarded-Proto $scheme;
          proxy_set_header X-Forwarded-Port $server_port;
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
          proxy_set_header Upgrade $http_upgrade;
          proxy_set_header Connection "upgrade";
        }

        location / {
          try_files $uri $uri/ @router;
          index  index.html;
        }

        location @router {           rewrite ^.*$ /index.html last;         }     } }

相關文章
相關標籤/搜索