我希望能够将 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/