openresty中几种重定向的差异比较(ngx.redirect、ngx.req.set_uri、ngx.exec)
一. 测试用的nginx.conf:
user root;
worker_processes 1;
error_log logs/error.log;
events {
worker_connections 1024;
}
http {
charset utf-8;
default_type application/octet-stream;
include /usr/local/openresty/nginx/conf/mime.types;
rewrite_by_lua_block {
ngx.log(ngx.ALERT, "(http | rewrite_by)新请求接入,是否内部重定向:" .. tostring(ngx.req.is_internal()))
}
access_by_lua_block {
ngx.log(ngx.ALERT, "(http | access_by)新请求接入,是否内部重定向:" .. tostring(ngx.req.is_internal()))
ngx.log(ngx.ALERT, "ngx.var.my_var: " .. tostring(ngx.var.my_var))
ngx.log(ngx.ALERT, "ngx.ctx.my_var: " .. tostring(ngx.ctx.my_var))
}
server {
listen 8080;
set $my_var "";
location /redirect {
rewrite_by_lua_block {
ngx.log(ngx.ALERT, "(location | rewrite_by | redirect)")
ngx.var.my_var = "redirect"
ngx.ctx.my_var = "redirect"
ngx.redirect("/final")
}
}
location /outside {
rewrite_by_lua_block {
ngx.log(ngx.ALERT, "(location | rewrite_by | outside)")
ngx.var.my_var = "outside"
ngx.ctx.my_var = "outside"
ngx.req.set_uri("/final", true)
}
}
location /inside {
access_by_lua_block {
ngx.log(ngx.ALERT, "(location | access_by | inside)")
ngx.var.my_var = "inside"
ngx.ctx.my_var = "inside"
ngx.req.set_uri("/final")
}
content_by_lua_block {
ngx.log(ngx.ALERT, "(location | content_by | inside)")
ngx.header.content_type = "text/html"
ngx.say("inside: <br>")
ngx.say("ngx.var.my_var: " .. tostring(ngx.var.my_var) .. "<br>")
ngx.say("ngx.ctx.my_var: " .. tostring(ngx.ctx.my_var) .. "<br>")
}
}
location /exec {
access_by_lua_block {
ngx.log(ngx.ALERT, "(location | access_by | exec)")
ngx.var.my_var = "exec"
ngx.ctx.my_var = "exec"
return ngx.exec('@hide')
}
}
location /mix {
access_by_lua_block {
ngx.log(ngx.ALERT, "(location | access_by | mix)")
ngx.var.my_var = "inside"
ngx.ctx.my_var = "inside"
ngx.req.set_uri("/final")
return ngx.exec('@hide')
}
}
location /final {
content_by_lua_block {
ngx.log(ngx.ALERT, "(location | content_by | final)")
ngx.header.content_type = "text/html"
ngx.say("final: <br>")
ngx.say("ngx.var.my_var: " .. tostring(ngx.var.my_var) .. "<br>")
ngx.say("ngx.ctx.my_var: " .. tostring(ngx.ctx.my_var) .. "<br>")
}
}
location @hide {
content_by_lua_block {
ngx.log(ngx.ALERT, "(location | content_by | hide)")
ngx.header.content_type = "text/html"
ngx.say("hide: <br>")
ngx.say("ngx.var.my_var: " .. tostring(ngx.var.my_var) .. "<br>")
ngx.say("ngx.ctx.my_var: " .. tostring(ngx.ctx.my_var) .. "<br>")
}
}
}
}
二. 测试结果
版权声明: 本文为博主 网无忌 原创文章,欢迎转载,但请务必标注原文链接。