diff --git a/openresty/lua/redis_helper.lua b/openresty/lua/redis_helper.lua index 8371e48..138c627 100644 --- a/openresty/lua/redis_helper.lua +++ b/openresty/lua/redis_helper.lua @@ -18,23 +18,21 @@ local function get_redis_connection() return nil end - -- Select the correct Redis database (db 1, matching backend config) - local db = tonumber(os.getenv("REDIS_DB")) or 1 - local res, err = red:select(db) - if not res then - ngx.log(ngx.ERR, "Failed to select Redis database: ", err) - return nil - end - - -- Authenticate if password is set + -- Authenticate FIRST if password is set (must happen before any other commands) if REDIS_PASSWORD and REDIS_PASSWORD ~= "" then local res, err = red:auth(REDIS_PASSWORD) if not res then ngx.log(ngx.ERR, "Failed to authenticate to Redis: ", err) return nil end - else - ngx.log(ngx.WARN, "No Redis password set, trying without auth") + end + + -- Select the correct Redis database (db 1, matching backend config) + local db = tonumber(os.getenv("REDIS_DB")) or 1 + local res, err = red:select(db) + if not res then + ngx.log(ngx.ERR, "Failed to select Redis database: ", err) + return nil end return red