NGINX仅为特定目录和索引文件指定变量

问题描述 投票:1回答:1

我正在使用fastcgi缓存,并希望指定缓存应该处于哪个URL。

我使用重写规则来确定要访问的控制器文件,并动态设置任何查询参数

我想指定激活缓存的URL以及缓存不活动的URL,这是我的代码:

server {
    listen 80;
    server_name domain.com;
    root /home/site/wwwroot;

    set %skip_cache 1;        #this is the variable that I want to set to 0 on specific URLS

    location / {
        try_files $uri $uri/ $uri.html @php;
    }
    location @php {         
        rewrite ^(/[^/]+)$ $1.php last;
        rewrite ^(/[^/]+)/(.*)$ $1.php?q=$2 last;
    }


    location /user/ {
        set $skip_cache 0;
    }

    location /objects/ {
        set $skip_cache 0;
    }

    location ~ \.php$  {
        try_files $uri =404;
        include fastcgi_params;
        fastcgi_pass unix:/run/php/php7.0-fpm.sock;
        fastcgi_split_path_info ^(.+?\.php)(/.*)?$;
        fastcgi_connect_timeout         300; 
        ...etc...

    #cache parameters
    fastcgi_param FASTCGI_CACHE 1;
    fastcgi_cache cfcache;
    fastcgi_cache_valid 30s;
    fastcgi_cache_bypass $skip_cache;
    fastcgi_no_cache $skip_cache;
    add_header X-FastCGI-Cache $upstream_cache_status;  
}

正如您所看到的,默认情况下变量$ skip_cache设置为1,我希望白名单URL用于缓存。

我想缓存的一个例子是domain.comdomain.com/user/123domain.com/objects/456

目前,如果我浏览到/user/123,结果是404错误,因为我认为具有变量设置的位置块是专门使用的。

regex nginx nginx-location nginx-reverse-proxy
1个回答
1
投票

如果要根据原始请求设置变量,则应使用带有map变量的$request_uri指令。有关详细信息,请参阅this document

例如:

map $request_uri $skip_cache {
    default      1;
    ~^/user/     0;
    ~^/objects/  0;
}
server {
    ...
    fastcgi_cache_bypass $skip_cache;
    fastcgi_no_cache $skip_cache;
    ...
}
© www.soinside.com 2019 - 2024. All rights reserved.