JAVA和Nginx 教程大全

网站首页 > 精选教程 正文

nginx+lua实现nginx高级应用

wys521 2024-09-17 02:20:55 精选教程 26 ℃ 0 评论

目录

  • 概述
  • lua介绍
  • 第一个nginx lua脚本
  • 用lua脚本实现IP访问限制
  • 使用lua做nginx的rewrite跳转
  • php7进阶到架构师相关阅读

概述

这是关于php进阶到架构之Nginx进阶学习的第篇文章:nginx+lua实现nginx高级应用

  • 第一篇:5分钟搞懂nginx的location匹配规则
  • 第二篇:nginx rewrite规则详解
  • 第三篇:5分钟上手nginx分流实战
  • 第四篇:Nginx跨域配置
  • 第五篇:深入理解浏览器缓存
  • 第六篇:nginx缓存以及gzip配置
  • 第七篇:nginx配置https
  • 第八篇:nginx+lua实现nginx高级应用

lua介绍

Lua 是一种轻量小巧的脚本语言,用标准C语言编写并以源代码形式开放, 其设计目的是为了嵌入应用程序中,从而为应用程序提供灵活的扩展和定制功能。

Nginx+Lua优势 - 充分的结合nginx的并发处理epool优势和Lua的轻量实现简单的功能高并发的场景

linux lua安装

 yum install lua

运行lua

[root@gofor]# lua
Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio
> print("hello world")
hello world

Nginx编译安装Lua模块

参考Nginx编译安装Lua模块【http://www.imooc.com/article/19597】

nginx调用lua模块指令

set_by_lua 设置nginx变量,可以实现复杂的复制逻辑

set_by_lua_file

access_by_lua 请求访问阶段处理,用于访问控制

access_by_lua_file

content_by_lua 内容处理器,接收请求处理并输出响应

content_by_lua_file

nginx lua api

ngx.var nginx变量

ngx.req.get_headers 获取请求头

ngx.req.get_uri_args 获取URL请求参数

ngx.redirect 重定向

ngx.print 输出响应内容体

ngx.say 同ngx.print,但是会在最后输出一个换行符

ngx.header 输出响应头

第一个nginx lua脚本

location /lua {
default_type text/plain;
content_by_lua 'ngx.say("hello world")';
}

访问xxxx.com/lua,浏览器将输出hello world

用lua脚本实现IP访问限制

location @client{
proxy_pass  http://www.gofor.com;
}
location ~  /test {
default_type  text/html;
access_by_lua '
if ngx.var.remote_addr == "101.2.20.110" then
ngx.exit(ngx.HTTP_FORBIDDEN)
end
if ngx.var.remote_addr == "10.2.20.112" then
ngx.exec("@client")
end
';
}

控制经过access_by_lua 访问权限判断之后,才能访问

用户访问xxxx.com/test时,如果客户端IP地址是101.2.20.110直接提示禁止访问;

如果客户端IP地址10.2.20.112时访问@client的location定义的处理

location / {
access_by_lua '
local res = ngx.location.capture("/auth")
if res.status == ngx.HTTP_OK then
return
end
if res.status == ngx.HTTP_FORBIDDEN then
ngx.exit(res.status)
end
ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
';
}

访问网站之前进行auth认证,并且作相应处理

使用lua做nginx的rewrite跳转

这个是先判断 check-pam接口的return的内容是不是spam,是的话,转跳到其他的页面

location / {
rewrite_by_lua '
local res = ngx.location.capture("/check-spam")
if res.body == "spam" then
ngx.redirect("/terms-of-use.html")
end
'; 
}

lua redirect的使用

return ngx.redirect("/foo")
return ngx.redirect("http://localhost:1984/foo", ngx.HTTP_MOVED_TEMPORARILY)
return ngx.redirect("/foo", 301)

返回302临时重定向 地址栏会显示跳转后的地址

php7进阶到架构师相关阅读

https://www.kancloud.cn/gofor/gofor

最后,欢迎大家留言补充,讨论~~~

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表