Tuesday, 14 October 2025

 

🔁 How to Build a Lightweight Round-Robin HTTP Redirector Using OpenResty

Sometimes, you only need simple HTTP redirection to multiple backend URLs in a round-robin fashion — without load balancers or proxying content.
Here’s how you can achieve it using OpenResty (NGINX + Lua).


🛠 Prerequisites

  • Ubuntu system (x86_64 / amd64)

  • Root or sudo privileges


1️⃣ Install OpenResty

# Install basic dependencies sudo apt-get -y install --no-install-recommends wget gnupg ca-certificates # Add OpenResty GPG key wget -O - https://openresty.org/package/pubkey.gpg | sudo apt-key add - # Add OpenResty repository echo "deb http://openresty.org/package/ubuntu $(lsb_release -sc) main" > openresty.list sudo cp openresty.list /etc/apt/sources.list.d/ # Update and install OpenResty sudo apt-get update sudo apt-get -y install --no-install-recommends openresty # Verify installation openresty -V

2️⃣ Configure NGINX for Round-Robin Redirects

Edit the main NGINX configuration file:

sudo vim /etc/openresty/nginx.conf

Add the following inside the http { ... } block:

# Shared memory zone to track counter lua_shared_dict rr_counter 1m; # Redirector server server { listen 80; server_name www.example.com; # Health check endpoint location /health { return 200 "OK"; } # Round-robin redirect location / { content_by_lua_block { local urls = { "https://www.example.com/page1", "https://www.example.com/page2", "https://www.example.com/page3", "https://www.example.com/page4", "https://www.example.com/page5" } local dict = ngx.shared.rr_counter local count = dict:get("count") or 0 count = (count % #urls) + 1 dict:set("count", count) local target = urls[count] return ngx.redirect(target, 302) } } }

How it works:

  • lua_shared_dict rr_counter 1m; creates a small shared memory segment to track the current URL index.

  • Each request increments the counter modulo the number of URLs.

  • NGINX issues a 302 redirect to the next URL in sequence.

  • /health endpoint can be used for load balancer or CloudFront health checks.


3️⃣ Reload OpenResty

sudo /usr/local/openresty/nginx/sbin/nginx -t # Test configuration sudo systemctl reload openresty # Reload OpenResty

4️⃣ Test the Redirect

for i in {1..10}; do curl -I http://www.example.com | grep Location; done

Expected output:

Location: https://www.example.com/page1 Location: https://www.example.com/page2 Location: https://www.example.com/page3 Location: https://www.example.com/page4 Location: https://www.example.com/page5 Location: https://www.example.com/page1 ...

Requests cycle through the URLs in order — true round-robin redirection.


✅ Advantages

  • Minimal server load (no content proxying)

  • True round-robin distribution

  • Works perfectly behind ELB or CloudFront

  • Easily extendable to multiple domains or URL lists