简体   繁体   中英

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.

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).

The static file may or may not be available to the logged out user, if not then I want php to handle the request

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) . 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. Also I have a static home page called index.html, and i'm not sure how to serve that either.

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. One approach is to use a regular expression location with a named capture. 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 / . The first if block redirects to PHP if the cookie exists (I think the logic in your question was inverted). The second if block tests for the presence of a matching cache file.

See this caution on the use of if .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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