Skip to content

Instantly share code, notes, and snippets.

@krazybean
Created April 17, 2018 02:12
Show Gist options
  • Select an option

  • Save krazybean/6161ddd690cc154166e2dc8b46ecbd31 to your computer and use it in GitHub Desktop.

Select an option

Save krazybean/6161ddd690cc154166e2dc8b46ecbd31 to your computer and use it in GitHub Desktop.
OpenResty config to read from redis
#user nobody;
worker_processes 5;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
location / {
resolver 8.8.4.4; # use Google's open DNS server
set $target '';
access_by_lua '
local key = ngx.var.http_user_agent
local ngxhost = ngx.req.get_headers()["Host"]
if not key then
ngx.log(ngx.ERR, "no user-agent found")
return ngx.exit(400)
end
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(1000) -- 1 second
local ok, err = red:connect("127.0.0.1", 6379)
if not ok then
ngx.log(ngx.ERR, "failed to connect to redis: ", err)
return ngx.exit(500)
end
local host, err = red:get(ngxhost)
if not host then
ngx.log(ngx.ERR, "failed to get redis key: ", err)
return ngx.exit(500)
end
if host == ngx.null then
ngx.log(ngx.ERR, "no host found for key ", key)
return ngx.exit(400)
end
ngx.var.target = host
';
proxy_pass http://$target;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment