重定向到Nginx列表中的随机条目

bhmjp9jg  于 2023-04-05  发布在  Nginx
关注(0)|答案(1)|浏览(169)

我希望能够将请求重定向到Nginx,从可能的选项列表中随机输入。
例如,我希望将对example.com/entryA的请求重定向到以下之一:

redirect.com/1
redirect.com/2
redirect.com/3

我知道这是可能的代理通行证和一个进程,实现这种逻辑,但我觉得这是矫枉过正。这是可能的Nginx没有过于复杂的事情?

x8goxv8g

x8goxv8g1#

似乎最简单的方法是使用安装了Lua的Nginx示例(我使用了https://github.com/fabiocicerchia/nginx-lua

http {
  server {
    listen 80;
    server_name example.com;

    location /entryA {
      content_by_lua_block {
        local redirects = {
          "http://redirect.com/1",
          "http://redirect.com/2",
          "http://redirect.com/3",
        }
        local random_url = redirects[math.random(1, #redirects)] 

        ngx.redirect(random_url)
      }
    }
  }
}
$ curl http://localhost:80/entryA -v
*   Trying 127.0.0.1:80...
* Connected to localhost (127.0.0.1) port 80 (#0)
> GET /entryA HTTP/1.1
> Host: localhost
> User-Agent: curl/7.83.1
> Accept: */*
> 
* Mark bundle as not supporting multiuse
< HTTP/1.1 302 Moved Temporarily
< Server: nginx/1.23.3
< Date: Sat, 01 Apr 2023 03:57:33 GMT
< Content-Type: text/html
< Content-Length: 145
< Connection: keep-alive
< Location: http://redirect.com/3
< 
<html>
<head><title>302 Found</title></head>
<body>
<center><h1>302 Found</h1></center>
<hr><center>nginx/1.23.3</center>
</body>
</html>
* Connection #0 to host localhost left intact

相关问题