nginx+lua实现修改url中文参数编码格式

文章讲述了如何在已经编译安装的Nginx中添加Lua模块,提供了编译命令示例。然后展示了Lua脚本,用于检测和转换URL中的中文参数,确保正确编码。通过`set_by_lua_file`指令在Nginx配置中应用这个脚本。
摘要由CSDN通过智能技术生成

nginx添加lua模块

    nginx是使用编译的方式安装的,所以重新编译安装。编译命令如下:
    ./configure --prefix=/eetop/nginx --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_addition_module --with-http_sub_module --with-http_dav_module --with-http_flv_module --with-http_mp4_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_random_index_module --with-http_secure_link_module --with-http_stub_status_module --with-mail --with-mail_ssl_module --with-file-aio --with-threads --user=www --group=www --add-module=/lua-nginx-module-0.10.15 --add-module=/ngx_devel_kit-0.3.1

–add-module=/lua-nginx-module-0.10.15 --add-module=/ngx_devel_kit-0.3.1为lua相关模块。

lua脚本

判断是否对中文进行编码

local function testchinese(val)
    local result = false
    for i = 1, string.len(val) do
        if string.byte(string.sub(val,i,i)) > 127 then
            return true
        else 
            result = false
        end 
    end 
    return result
end

对url中的中文参数进行编码

local function transfergbktoutf(val)
    local result = ""
    local iconv = require("iconv")
    local cd = iconv.new("utf-8" .. "//TRANSLIT", "gb2312")
    local ostr, err = cd:iconv(val)
    if #val > #ostr then
        result = ngx.escape_uri(val)
    elseif testchinese(val) == true then
        result = ngx.escape_uri(val)
    else
        result = ngx.escape_uri(ostr)
    end
    return result
end
local argall = ngx.req.get_uri_args()获取url中参数

对参数进行转码

if argall==nil then
    return argall
else
    for k,v in pairs(argall) do
        if argall[k]=="" or argall[k]==true then
            decodeargs = decodeargs..k.."=".."&"
        elseif argall[k]==true then
            decodeargs = decodeargs..k.."&"
        else
          if type(argall[k]) == "table" then
              for k1,val in pairs(argall[k]) do                
                  value = transfergbktoutf(val)
                  decodeargs = decodeargs..k.."="..value.."&"
              end
          else
              value = transfergbktoutf(v)
              decodeargs = decodeargs..k.."="..value.."&"
          end
        end
    end
    decodeargs = string.sub(decodeargs, 1, -2)
end

nginx配置

在对应的location里面添加
set_by_lua_file $args /home/www/transchinesearg.lua

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值