Python1320

nginx case insensitive file search with lua

Oct 11th, 2012
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.65 KB | None | 0 0
  1. local start=os.clock()
  2. local string=string
  3.  
  4.  
  5. local lfs=require"lfs"
  6. function isdir(fn)
  7.    
  8.     return (lfs.attributes(fn, "mode") == 'directory')
  9. end
  10. function exists(fn)
  11.     return lfs.attributes(fn, "mode")
  12. end
  13.  
  14. local function findcorrect(path,what)
  15.     local ok,a,b,c,d=pcall(lfs.dir,path)
  16.     if not ok then return false,a end
  17.    
  18.     what=what:lower()
  19.    
  20.     local found=false
  21.     for file in a,b,c,d do
  22.         if file ~= "." and file ~= ".." then
  23.             if file:lower()==what then
  24.                 found=file
  25.                 break
  26.             end
  27.         end
  28.     end
  29.    
  30.     return found
  31. end
  32.  
  33.  
  34. ngx.status=ngx.HTTP_NOT_FOUND
  35. status = ngx.status
  36. local root=ngx.var.document_root
  37. local url=ngx.var.uri
  38.  
  39.  
  40. -- find it the easy way
  41. local reqpath,delim,reqfile=url:match("(.*)([/\\])(.+)")
  42. local path=ngx.var.document_root..reqpath--lfs.currentdir()
  43. local correct=findcorrect(path,reqfile)
  44. if correct then
  45.     ngx.status=ngx.HTTP_MOVED_PERMANENTLY
  46.     status = ngx.status
  47.     local f = reqpath..delim..correct
  48.     return ngx.redirect(f, ngx.HTTP_MOVED_PERMANENTLY)
  49. end
  50.  
  51. -- nope, let's find it the hard way. ADD CACHING D:
  52. local nowpath=""
  53. for str in url:gmatch"[^/]+" do
  54.     local dir=exists(root..nowpath..str)
  55.     local setstr
  56.    
  57.     if not dir then
  58.         setstr=findcorrect(root..nowpath,str)
  59.     else
  60.         setstr=str
  61.     end
  62.     if not setstr then nowpath=false  break end
  63.     nowpath=nowpath..'/'..setstr
  64.    
  65. end
  66. if nowpath then
  67.     ngx.status=ngx.HTTP_MOVED_PERMANENTLY
  68.     status = ngx.status
  69.     return ngx.redirect(nowpath, ngx.HTTP_MOVED_PERMANENTLY)
  70. end
  71.  
  72. ngx.status=ngx.HTTP_NOT_FOUND
  73. status = ngx.status
  74. ngx.say(string.format("Sorry, couldn't find that file. I looked it for: %.2f\n", os.clock() - start))
  75. return ngx.exit(ngx.HTTP_NOT_FOUND)
Advertisement
Add Comment
Please, Sign In to add comment