skip to Main Content

How to get a part of url?

For example:
have url: /aaa/bbb/ccc?test=123

I need to get part of url /ccc into the nginx variable.

I want to get a variable with a value = "ccc"

I will use the variable in location {}

2

Answers


  1. url  = '/abc/def/ghi?test=123'
    -- here ^  to here  ^  then back 1
    
    q = url :find('?')
    head = url :sub( 1,  q -1 )  --  /abc/def/ghi
    
    --  reversing is just an easy way to grab what would
    --  would be the last delimiter, but is now the first.
    
    head = head :reverse()  --  ihg/fed/cba/
    slash = head :find('/') -- 1st ^
    
    --  same as above, grab from beginning, to found position -1
    
    folder = head :sub( 1, slash -1 )  --  ihg
    folder = folder :reverse()  --  ghi
    
    --  reverse again, so it's right-way 'round again.
    

    Commands can be stacked, to make it smaller. Harder
    to explain the logic that way, but it’s the same thing.

    head = url :sub( 1, url :find('?') -1 ) :reverse()
    folder = head :sub( 1, head :find('/') -1 ) :reverse()
    
    Login or Signup to reply.
  2. I would suggest to use a library, available from official OpenResty Package Manager OPM:

    opm install bungle/lua-resty-reqargs
    

    This library works for both GET and POST variables:

    local get, post, files = require "resty.reqargs"()
    if not get then
      local ErrorMessage = post
      error(ErrorMessage)
    end
    
    -- Here you basically have `get' which is a table with:
    -- { test = 123 }
    

    The API is a little bit weird because the function returns 3 values.
    In case of failure, it will return false, ErrorMessage, false.
    In case of success, it will return GetTable, PostTable, FilesTable. Except this, it just works.

    You can use it in a location block:

    location /aaa/bbb/ccc {
      content_by_lua_block {
        local get, post, files = require "resty.reqargs"()
        if not get then
          local ErrorMessage = post
          ngx.say(ErrorMessage)
        else
          ngx.say(string.format("test=%d", get.test))
        end
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search