URL Rewrite

server.rewrite() method is used to point url to specific resource based on regex pattern

url.rewrite(string <*pattern>, mix <resource>, string <subject=req.uri>) : bool


This method support pattern, resource, subject parameters

Only Pattern is required.


The pcrc regex pattern.


Optional. Can Be a Page Name or Callback Function.


The Subject To test for match default is req.uri

Return Values

Returns true if there is a match, false otherwise. If page Name is specified then page will be shown. If Callback if provided function call will be returned full matching array will be passed to function.


Example #1 Simple Test

This will Show Test Msg on test page:

if url.rewrite("/test") then server.send("Test success") end

Example #2 Display single Page

display single page for all request:

url.rewrite("*", "index"); ---> display index page for all request

Example #3 Display Page dynamically

If page not exist on server we can show error msg this way:

if not url.rewrite("*", req.script_name or "index") then server.error("Error Page Not Found", 404); end

Example #4 Display msg 

Try to serve static template File If not found then try to show page or error page

url.rewrite("/ok", function () print("Hi "..env.username) end); ---> display Hi when you go to /ok

url.rewrite method is very useful for handling requests correctly and display appropriate content.