nginx中的sub_filter

需求/問題

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

由於有嚴格的端口限制(對外暴露80端口) 所以我們在右邊的服務器纔有一個nginx來根據api path做反向代理.

因爲想把我們的代碼跟CI jenkins集成, 所以想找個辦法來看看怎麼將jenkins也通過代理服務器的80端口訪問?

步驟

step1:

我們將/j/的路徑訪問到jenkins服務器地址.  比如服務器爲: test.com, 那麼我們通過test.com/j/來訪問jenkins:

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

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

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';
    }       

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

sub_filter '/login' '/j/login';   --- 這個我們發現返回值裏面有重定向 所以我們需要把jenkins返回的內容進行替換重寫. sub_filter       sub_filter '/adjuncts' '/j/adjuncts';  -- 這個也是類似.  但是的多用firefox/chrome的開發者工具才看得出來 有哪些返回失敗.

注意只有在新版本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;
        }
    }
}

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章