简体   繁体   English

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

[英]if Nginx does not find a http_cookie then try serving a static file, otherwise fallback to php

I'm relatively new to nginx and am struggling to understand some of it's concepts. 我对nginx相对较新,并且正在努力了解其中的一些概念。

I have a php application, I also have static html files which I wish to serve to uses who are not logged in. I can determine this by the presence of an http cooke ( which 'loggedin' will be set to 1 if logged in or it will not to present or set to 0 if the user is not). 我有一个php应用程序,我也有一些静态html文件,我希望使用这些文件供未登录的用户使用。我可以通过http cooke的存在来确定它(如果登录或将'loggedin'设置为1,如果没有,则不会显示或设置为0)。

The static file may or may not be available to the logged out user, if not then I want php to handle the request 静态文件可能对注销的用户可用或不可用,如果没有,那么我希望php处理请求

My best attempt at solving this is like this 我最大的尝试来解决这个问题是这样的

location / {
    if ($http_cookie ~* "loggedin" ) {
        set $cachepath '/cache$request_uri.html';

    }
    try_files $cachepath $uri /index.php?$query_string;

}

But that does not work. 但这不起作用。 Also worth noting is my php application serves urls like so www.website.com/about-us/ (with a trailing slash on the end) . 同样值得注意的是,我的php应用程序提供的网址也是如此,例如www.website.com/about-us/(末尾带有斜杠)。 So looking for the cache file like above, will look like this cache/about-us/.html when it should be this cache/about-us.html. 因此,如上查找缓存文件时,该缓存文件应为cache / about-us.html。 Also I have a static home page called index.html, and i'm not sure how to serve that either. 另外,我有一个名为index.html的静态主页,但我不确定该如何服务。

Thanks to anyone who can help me. 感谢任何可以帮助我的人。

You need to extract the basename from the URI with the trailing / and then test if the file exists. 您需要从URI尾随/提取基本名称,然后测试文件是否存在。 One approach is to use a regular expression location with a named capture. 一种方法是使用带有命名捕获的正则表达式location See this document for more. 有关更多信息,请参见此文档

For example: 例如:

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$ { ... }

The first location block only handles URIs consisting of a name and a trailing / . 第一个location块仅处理由名称和结尾/组成的URI。 The first if block redirects to PHP if the cookie exists (I think the logic in your question was inverted). 如果cookie存在,第一个if块将重定向到PHP(我认为您问题中的逻辑已倒置)。 The second if block tests for the presence of a matching cache file. 第二个if块测试是否存在匹配的缓存文件。

See this caution on the use of if . 请参阅有关使用if 注意事项

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM