如果 Nginx 找不到http_cookie则尝试提供静态文件,否则回退到 php



我对nginx比较陌生,正在努力理解它的一些概念。

我有一个php应用程序,我也有静态html文件,我希望为未登录的用户提供服务。我可以通过 http cooke 的存在来确定这一点(如果登录,"登录"将设置为 1,或者如果用户未登录,则不会显示或设置为 0(。

静态文件可能对注销的用户可用,也可能不可用,如果不是,那么我希望 php 处理请求

我解决这个问题的最佳尝试是这样的

location / {
if ($http_cookie ~* "loggedin" ) {
set $cachepath '/cache$request_uri.html';
}
try_files $cachepath $uri /index.php?$query_string;
}

但这行不通。另外值得注意的是,我的php应用程序提供像这样 www.website.com/about-us/的URL(末尾有一个尾部斜杠(。因此,查找如上所述的缓存文件,将如下所示 cache/about-us/.html 什么时候应该是这个 cache/about-us.html。 此外,我有一个名为index.html的静态主页,我也不确定如何提供它。

感谢任何可以帮助我的人。

您需要从带有尾随/的 URI 中提取基名称,然后测试该文件是否存在。一种方法是将正则表达式location与命名捕获一起使用。有关详细信息,请参阅此文档。

例如:

location ~ ^/(?<name>[^/]+)/ {
if ($http_cookie ~* "loggedin") {
rewrite ^ /index.php last;
}
if (-f $document_root/cache/$name.html) { 
rewrite ^ /cache/$name.html last;
}
rewrite ^ /index.php last;
}
location / { ... }
location ~ .php$ { ... }

第一个location块仅处理由名称和尾随/组成的 URI。如果 cookie 存在,第一个if块会重定向到 PHP(我认为您问题中的逻辑被颠倒了(。第二个if块测试是否存在匹配的缓存文件。

请参阅此注意事项 使用if.

最新更新