[英]Nginx Redirect to Cookie-Consent Page if Consent Cookie not Set
这个问题几乎与这个问题相反。 由于 nginx 只允许if
和if
子句内只允许return
、 rewrite
和proxy_pass
等,但try_files
和else
或NOT
可能不会被使用。
所以问题:我想 model 以下(在伪 nginx 配置中)
location / {
if (NOT isset(cookie("cookie-consent")) ) {
return 302 "https://example.com/cookieconsent";
}
else {
# I am running the site on a backend server
proxy_pass https://example.com:8443;
}
}
# The HTML here has a button to agree to the use of said cookies
location /cookieconsent {
root /path/to/www-root;
try_files $uri/index.html $uri.html;
}
location /setconsent {
add_header Set-Cookie 'consent=true;Domain=$host;Path=/;Max-Age=7776000;SameSite=strict;HTTPOnly;Secure';
return 302 https://$host;
}
这样做的背景是我正在使用 Nextcloud 并且由于 Nextcloud 仅使用功能 cookies,因此通过弹出窗口告知用户 cookies 的使用就足够了,但是 Nextcloud 没有 GDPR Cookie Consent 插件,我也没有兴趣开发一个. 因此,最简单的替代方法是检查用户是否已被告知使用 cookies 并首先显示 cookie 同意页面,否则在显示实际站点之前。
与 nginx 一样强大,当然有解决上述问题的有效方法。 实际上,我添加问题的原因是发布此答案,因为我相信它可能会对其他人有所帮助,当然我也是如此,以防我忘记了随着时间的推移我是如何实现它的,并在谷歌上寻求快速解决方案。 事不宜迟,这是我在 nginx 配置文件中的解决方案:
location / {
proxy_set_header HOST example.com;
proxy_set_header X-Forwarded-For $remote_addr;
if( $http_cookie ~* "consent" ) {
proxy_pass https://example.com:8443;
}
# Setting `return 302` directly here doesn't work well
# the first argument is just a filler as entering '@noconsent' only is disallowed
try_files $uri/$arg_key @noconsent;
}
location @noconsent {
return 302 "https://example.com/cookieconsent";
}
location /cookieconsent {
root /path/to/www-root;
expires max;
try_files $uri/index.html $uri.html;
}
location /setconsent {
add_header Set-Cookie 'consent=true;Domain=$host;Path=/;Max-Age=7776000;SameSite=strict;HTTPOnly;Secure';
return 302 https://$host;
}
如果未设置 cookie,此配置的作用是 302 重定向到“https://example.com/cookieconsent”。 在那里,它搜索“/cookieconsent/index.html”和“cookieconsent.html”。 这些文件中的任何一个都应该存在并且可由服务器读取。 它还应该包括触发“/setconsent”的按钮或链接。 然后,设置consent
cookie,使得条件为true
并触发proxy_pass
(在这种情况下加载Nextcloud)。
这样做的好处是,在访问者按照 GDPR 法律的要求明确同意之前,可以完全在 HTML 中执行此操作,而无需设置任何 cookies。 另一方面,访问者在不同意使用 cookies 之前不能访问实际网站。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.