基于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

原文地址:https://www.cnblogs.com/rongfengliang/p/13388375.html