OpenResty = Nginx 核心 + 大量第三方模組(lua-nginx-module、redis2、upstream 等)+ LuaJIT。將 Lua 直接嵌入 Nginx 階段,實現高效能非阻塞邏輯處理。
# Ubuntu
wget https://openresty.org/package/pubkey.gpg -O- | sudo apt-key add -
echo "deb https://openresty.org/package/ubuntu $(lsb_release -sc) main" \
| sudo tee /etc/apt/sources.list.d/openresty.list
sudo apt update && sudo apt install openresty
# macOS
brew install openresty
nginx.confworker_processes 1;
error_log logs/error.log;
events { worker_connections 1024; }
http {
server {
listen 80;
server_name localhost;
location /lua {
default_type text/plain;
# 直接執行 Lua 程式碼
content_by_lua_block {
ngx.say("Hello World from OpenResty!")
}
# 或載入外部檔案
# content_by_lua_file /opt/lua/bin/test.lua;
}
}
}
/opt/lua/bin/test.lualocal welcome = "Hello World from external Lua file"
ngx.say(welcome)
# 前景運行(開發測試)
openresty -p `pwd` -c nginx.conf
# 瀏覽器訪問 https://localhost/lua
# 輸出: Hello World from external Lua file
| 指令 | 階段 | 用途 |
|---|---|---|
content_by_lua_block | Content | 直接內嵌 Lua 代碼 |
content_by_lua_file | Content | 載入外部 .lua 檔案 |
access_by_lua* | Access | 存取控制、驗證、限流 |
rewrite_by_lua* | Rewrite | URL 重寫、內部跳轉 |
log_by_lua* | Log | 非同步記錄日誌 |
os.execute、socket.sleep 等阻塞呼叫,需用 ngx.sleep、lua-resty-* 非阻塞庫。local 或 ngx.ctx 隔離請求資料。lua_code_cache off:開發時關閉快取即時生效,生產**必須開啟**。OpenResty 讓 Nginx 搖身一變為可編程應用伺服器。從 Hello World 開始,探索 lua-resty-redis、lua-resty-http、lua-resty-jwt 生態,構建高效能 API 閘道、邊緣計算、即時推播等場景。