【问题标题】:NGINX specify variable for specific directory and index file onlyNGINX 仅为特定目录和索引文件指定变量
【发布时间】:2019-02-18 06:35:04
【问题描述】:

我正在使用 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】:

    如果您想根据原始请求设置变量,您应该使用带有$request_uri 变量的map 指令。详情请见this document

    例如:

    map $request_uri $skip_cache {
        default      1;
        ~^/user/     0;
        ~^/objects/  0;
    }
    server {
        ...
        fastcgi_cache_bypass $skip_cache;
        fastcgi_no_cache $skip_cache;
        ...
    }
    

    【讨论】:

    • 谢谢,效果很好!你知道如何让它也命中索引文件,例如domain.com被重写为domain.com/index.php如何让该索引文件也被列入白名单?
    • 您可以在map 中添加/ 0; 行和~^/index.php 0; 行。
    猜你喜欢
    • 1970-01-01
    • 2016-07-21
    • 2014-11-05
    • 2013-04-11
    • 2019-09-02
    • 1970-01-01
    • 2019-06-12
    • 2020-10-22
    • 1970-01-01
    相关资源
    最近更新 更多