基於openresty進行 query string 重寫


主要目前很簡單就是移除nginx request 中的query_string,因為rewrite 階段處理的是uri ,不包含query_string,但是rewrite 會保持 
原query_string ,我們可以通過args 變量重寫,當然也可以基於openresty 的 ngx.req.set_uri_args 重寫,從代碼的簡潔以及擴展上 
基於openresty 更好點,以下是一個簡單的demo說明

需求

  • 格式
    /demo/?name=demo
    重寫為
    /demo/

環境准備

  • docker-compose 文件
 
version: "3"
services: 
  api:
    image: openresty/openresty:alpine
    volumes:
    - "./nginx.conf:/usr/local/openresty/nginx/conf/nginx.conf"
    - "./demoapps:/opt/demoapps"
    ports:
    - "80:80"
    - "8080:8080"
 
 
  • nginx.conf
user root;  
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    gzip  on;
    rewrite_log on;
    real_ip_header     X-Forwarded-For;
    server {
       listen 80;
       charset utf-8;
       default_type text/html;
       location / {
           root /opt/demoapps;
            index index.html index.htm index;
       }
       location ~* ^/demo {
           root /opt/demoapps;
           rewrite_by_lua_block {
               -- format /demo/index.html?name=dalong
              // 基於re.sub 當然也可以使用match 進行處理
               local uri,n,err = ngx.re.sub(ngx.var.request_uri, [[^\/(.+)\/(.+)\?(.+)]], "/$1/$2", "o")
                ngx.log(ngx.ERR,"fetch---"..uri..[[---------]]..ngx.var.request_uri)
                if n >  0 then
                   -- you can also set uri
                   -- ngx.req.set_uri(uri,false)
                   ngx.req.set_uri_args({a="dalong"})
                end
            }
            content_by_lua_block {
            local cjson  = require("cjson.safe");
            local info = {
                request_uri = ngx.var.request_uri,
                query_string = ngx.var.query_string
            }
            ngx.say(cjson.encode(info))
          }
        }
    }
} 
  • 啟動
docker-compose up -d

效果

 

 

說明

nginx 的request_uri 變量是只讀的,不可修改的,實際使用查詢字符串,推薦使用query_string
一個完整的使用參考/index.html$is_args$query_string 此配置對於但頁面應用是比較有意義的
$is_args 表示是否攜帶query_string 包含了為? 沒有為空

參考資料

http://nginx.org/en/docs/varindex.html
https://github.com/openresty/lua-nginx-module#ngxreqset_uri_args


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM