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

标签 nginx

我希望能够将 Nginx 的请求重定向到可能选项列表中的随机条目。

例如,我希望将 example.com/entryA 的请求重定向到以下位置之一:

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

我知道这可以通过代理传递和实现此逻辑的进程来实现,但我觉得这有点矫枉过正。 Nginx 是否可以在不使事情过于复杂的情况下实现这一点?

最佳答案

似乎最简单的方法是使用安装了 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

关于nginx - 重定向到 Nginx 列表中的随机条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75895049/

相关文章:

module - 这个包可以重新编译吗

django - AWS 上的 nginx 和 Gunicorn 出现 504 超时

performance - Netty vs Nginx : Pros and Cons based on Performance, 内存管理,内存占用

docker - nginx 的 gitlab 容器代理传递不适用于推送请求

ruby-on-rails-3 - 乘客+Nginx显示自定义500页面

ssl - Nginx 反向代理力 https

php - Nginx 将参数传递给 PHP 文件

linux - NGINX:允许多个端口可用于 https + 将所有 http 重定向到 https

django - Django + nginx + uwsgi 无法登录

c++ - Nginx 有符号整数,CVE-2013-2028