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

相关文章
相关标签/搜索