Nginx; if is evil, but Lua rocks

Nginx is a web server that is designed on asynchronous, non-blocking, event-driven connection handling algorithm. As of this writing according to W3Techs Nginx serves around 32.2% websites known to them. At Wego we use Nginx as our primary web server.

Recently Wego launched its mobile website as a Progressive Web App: PWA, for significant visible speed and performance gains. This replaced our previous version of adaptive website. The challenge on the Nginx side for the launch was to keep serving the users under same domains i.e. over 50 domains for Wego, and redirecting users to PWA site for Mobile and the Desktop user to the current version.

Previously we have had a similar situation implementing a security system at our proxy level where we had to route our requests through a system sitting beside our proxy. For that we used Nginx if statement in each location block, and I can not reiterate enough on its evilness and the unexpected behaviour that it brings along its implementation, considering the size of our configurations, it was an excruciating task, since then we don't use the builtin if anymore. In Nginx's own word if is evil, so it is better to avoid their use.

So what is it that we use other than the available command set ? one solution was to have new end points for mobile user or redirect them from old landing pages to the new urls or solve the whole thing by redirecting them to a separate mobile (sub)domains, such practices are quite common where you see, or for new launched/demo products. We didn't want the user experience to be effected, for that the new PWA based mobile website was to be served seamlessly under the same domains and urls. The major advantage that this brought was the SEO and SEM campaigns that were currently in place , with significant amount invested to generate traffic they didn't go obsolete and were able to draw traffic to the new PWA website.

Concluding on how if's are evil and that user experience takes precedence over all. The solution was to use a lesser known brilliance that Nginx supports i.e Lua. Not many know and not much is available on the internet either about how Lua can be used to make Nginx respond to your requirements. The flavour of Nginx that has the lua-nginx-module built into it is Openresty, if you want you can compile and build Nginx with the module(s) as well. With Lua support you can assign variables, add logging, update/change request/response variables and select proxy_pass dynamically. All with the freedom and reliability of knowing it performs the way you expect it to. With Lua added to our stack we continue to achieve more and solve new challenges.

View Comments