hi, thanks for this
can I Route on cookies, similar to this question: Is it possible to modify Router matches based on cookies like in Varnish? - #3 by dimitarvp
I want to be able to present a static cached page using http_cache | Hex if no cookies and if there are cookies I want to route to a non cached cookied page
in Varnish you can do:
sub vcl_hash {
if (req.http.cookie ~ "wordpress_logged_in_") {
hash_data("wordpress_logged_in");
}
# the builtin.vcl will take care of also varying cache on Host/IP and URL
}
or better
import cookie;
import directors;
import std;
import kvstore;
sub vcl_init {
kvstore.init(0, 1000);
}
sub vcl_backend_response {
set beresp.http.x-tmp = regsub(header.get(beresp.http.set-cookie,"JSESSIONID=", " *;.*", "");
if (beresp.http.x-tmp != "") {
kvstore.set(0, cookie.get("id"), beresp.backend, 15m);
}
unset beresp.http.x-tmp;
}
sub vcl_recv {
cookie.parse(req.http.cookie);
set req.http.server = kvstore.get(0, cookie.get("id"), "none");
if (req.http.server == "s1") {
set req.backend_hint = s1;
} else if (req.http.server == "s2") {
set req.backend_hint = s2;
} else {
if (std.rand(0, 100) < 50) {
req.backend_hint = s1;
} else {
req.backend_hint = s2;
}
}
return (pass);
}
https://varnish-cache.org/docs/trunk/reference/vmod_cookie.html
or in Nginx, you can define a map in http section:
map $cookie_proxy_override $my_upstream {
default default-server-or-upstream;
~^(?P<name>[\w-]+) $name;
}
Then you simply use $my_upstream
in location section(s):
location /original-request {
proxy_pass http://$my_upstream$uri;
}
Nginx evaluates map variables lazily, only once (per request) and when you are using them.
server {
...
set $upstream "default-server-or-upstream";
if ($http_cookie ~ "proxy_override=([\w-]+)") {
set $upstream $1;
}
location /original-request {
proxy_pass http://$upstream/original-application
}
}
I asked Brave search AI and it gave me:
defmodule MyApp.Router do
use Plug.Router
plug :match
plug :dispatch
get "/hello" do
case get_req_header(conn, "cookie") do
[{"cookie_value"}] -> send_resp(conn, 200, "Cookie matched")
_ -> send_resp(conn, 400, "Cookie not matched")
end
end
end
or
defmodule MyApp.Router do
use Plug.Router
plug :match
plug :dispatch
get "/set-cookie" do
domain = PublicSuffix.registrable_domain(conn.host)
opts = [store: :cookie, key: "_myapp_key", signing_salt: "asdadl", domain: domain, max_age: max_age, http_only: true]
opts = Plug.Session.init(opts)
conn = Plug.Session.call(conn, opts)
send_resp(conn, 200, "Cookie set")
end
end