Nginx:根据 HTTP 方法处理位置

Nginx:根据 HTTP 方法处理位置

我想从缓存中处理所有对 /api 的 [GET] 请求,并像在最后一个位置块中一样处理所有其他请求(不使用缓存)。所有使用 PUT、POST、DELETE 方法对 /api 的请求也不必使用缓存。

我在这里看到了类似的问题根据请求方法进行 Nginx 代理,但仍然不明白在我的情况下如何使用它。

提前致谢。

我的配置:

location / {
    root /var/www/project/web;
    # try to serve file directly, fallback to app.php
    try_files $uri /app.php$is_args$args;
}


location ~ ^/api {
    root /var/www/project/web/app.php;
    fastcgi_send_timeout 600s;
    fastcgi_read_timeout 600s;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_split_path_info ^(.+\.php)(/?.*)$;
    include fastcgi_params;
    fastcgi_cache fcgi;
    fastcgi_cache_valid 200 5m;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param HTTPS off;

}

location ~ ^/(app|app_dev|config)\.php(/|$) {
    root /var/www/project/web;
    fastcgi_send_timeout 600s;
    fastcgi_read_timeout 600s;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_split_path_info ^(.+\.php)(/?.*)$;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param HTTPS off;
}

答案1

我的问题在这里得到了回答stackoverflow.com/a/35291314/1517230由聪明的 stackoverflow 用户提供 :)

location ~ ^/api {
    root /var/www/project/web/app.php;
    fastcgi_send_timeout 600s;
    fastcgi_read_timeout 600s;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_split_path_info ^(.+\.php)(/?.*)$;
    include fastcgi_params;

    # Don't cache anything by default
    set $no_cache 1;

    # Cache GET requests
    if ($request_method = GET)
    {
        set $no_cache 0;
    }

    fastcgi_cache_bypass $no_cache;
    fastcgi_no_cache $no_cache;

    fastcgi_cache fcgi;
    fastcgi_cache_valid 200 5m;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param HTTPS off;
}

或者

map $request_method $api_cache_bypass {
    default       1;
    GET           0;
}

location ~ ^/api {
    root /var/www/project/web/app.php;
    fastcgi_send_timeout 600s;
    fastcgi_read_timeout 600s;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_split_path_info ^(.+\.php)(/?.*)$;
    include fastcgi_params;

    fastcgi_cache_bypass $api_cache_bypass;
    fastcgi_no_cache $api_cache_bypass;

    fastcgi_cache fcgi;
    fastcgi_cache_valid 200 5m;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param HTTPS off;
}

相关内容