search

Nginx and Lua

Quotations from Fire Cloud Evil God: In martial arts in the world, nothing is unbreakable, only speed! Nginx's specialty is speed, and Lua's specialty is speed. The combination of the two undoubtedly has a genetic advantage in speed.

OpenResty was the first to combine Nginx and Lua. It has an ngx_lua module that embeds Lua into Nginx; then Tengine also included the ngx_lua module. As for the difference between the two: OpenResty is the Bundle of Nginx; while Tengine is the Fork of Nginx. It is worth mentioning that OpenResty and Tengine are both projects created by Chinese people. The former is mainly developed by Chun Ge and Xiaozhe, and the latter is mainly managed by Taobao.

As for the advantages and disadvantages of OpenResty and Tengine, it is left to everyone to judge for themselves. The following information is available for reference:

  • ngx_openresty: an Nginx ecosystem glued by Lua
  • Taobao Nginx application, customization and development practice

Recommended to read the transcript of Brother Chun's speech on "Nginx Ecological Environment Glued by Lua" at Tech-Club, there is information!

Installation

requires the latest version of Nginx, LuaJIT, ngx_devel_kit, ngx_lua and other installation files.

It is possible to install Lua or LuaJIT, but for efficiency reasons, it is recommended to install LuaJIT.

shell> wget http://luajit.org/download/LuaJIT-.tar.gz shell> tar zxvf LuaJIT-.tar.gz shell> cd LuaJIT- shell> make shell> make install

Because it is installed in the default path, the lib and include corresponding to LuaJIT are all in the /usr/local directory.

shell> export LUAJIT_LIB=/usr/local/lib shell> export LUAJIT_INC=/usr/local/include/luajit-

Now you can compile Nginx:

shell> wget http://nginx.org/download/nginx-.tar.gz shell> tar zxvf nginx-.tar.gz shell> cd nginx- shell> ./configure --add-module=/path/to/ngx_lua \ --add-module=/path/to/ngx_devel_kit shell> make shell> make install

Try to start Nginx and see if you are unlucky, you may encounter the following error:

cannot open shared object file: No such file or directory

Is this a crazy situation? You can use the ldd command to check:

shell> ldd /path/to/nginx libluajit-.so => not found

Such problems can usually be solved using the ldconfig command:

shell> echo "/usr/local/lib" > /etc/ld.so.conf.d/usr_local_lib.conf shell> ldconfig

Try to start Nginx again and it should be OK.

Application

Let’s warm things up first with a simple program: add the following code to Nginx’s configuration file nginx.conf, restart Nginx, and then browse to see the effect.

location /lua { set $test "hello, world."; content_by_lua ' ngx.header.content_type = "text/plain"; ngx.say(ngx.var.test); '; }

Before learning ngx_lua in depth, it is recommended that you carefully read the Nginx tutorial written by Brother Chun.

Here I will talk about the key point: the language used in the Nginx configuration file is essentially "declarative" rather than "procedural". When Nginx processes a request, the execution of instructions is not determined by the physical order when the instructions are defined, but depends on the stage to which the instructions belong. The commonly used stages in Nginx are: rewrite stage, access stage, content stage, etc. . The set instruction in the demo code belongs to the rewrite stage, and the content_by_lua instruction belongs to the content stage. If you try to exchange the order of the two instructions, you will find that the program can still run normally.

Let’s try to write a more practical example using Redis.

First, we need to create a Redis configuration file config.json with the following content:

{ "host": "", "port": "" }

Then, we create a script init.lua that parses the configuration file, which uses Lua CJSON module:

local cjson = require "cjson"; local config = ngx.shared.config; local file = io.open("config.json", "r"); local content = cjson.decode(file:read("*all")); file:close(); for name, value in pairs(content) do config:set(name, value); end

Description: Shared memory is used in the code, so that the configuration file does not need to be parsed for every request.

Next, we create a script content.lua that renders content, using Resty Redis module:

ngx.header.content_type = "text/plain"; local redis = require "resty.redis"; local config = ngx.shared.config; local instance = redis:new(); local host = config:get("host"); local port = config:get("port"); local ok, err = instance:connect(host, port); if not ok then ngx.log(ngx.ERR, err); ngx.exit(ngx.HTTP_SERVICE_UNAVAILABLE); end instance:set("name", "laowang"); local name = instance:get("name") instance:close(); ngx.say("name: ", name);

Note: It is recommended to put the Resty Redis module in the vendor directory and set it up in Nginx later.

Finally, we need to set it in the Nginx configuration file:

lua_shared_dict config 1m; lua_package_path "/path/to/vendor/?.lua;;"; init_by_lua_file /path/to/init.lua; server { lua_code_cache off; location /lua { content_by_lua_file /path/to/content.lua; } ... }

Note: To facilitate debugging, I turned off lua_code_cache. If it is a production environment, it should be turned on.

In addition, when installing CJSON, you need to pay attention to the path of the header file in the Makefile. The default is:

PREFIX = /usr/local LUA_INCLUDE_DIR = $(PREFIX)/include

If you are installing LuaJIT, it is best to copy the header file to the corresponding directory:

cp /usr/local/include/luajit-/* /usr/local/include/

I recently participated A project of , which provides some interfaces for Web polling, all implemented using Nginx + Lua. Although there are only a dozen servers in total, it can provide billions of requests every day, which is very powerful.

Finally, let me conclude by quoting a quote from a loser: Lua is the favorite of unmarried male programmers.

This entry was published by Lao Wang in the Technical category and tagged Lua and Nginx. The fixed link Add to Favorites.

There are 29 comments on "NGINX and LUA"


The above has introduced the nginx tutorial, including various aspects. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.