【问题标题】:Debian 9 - nginx ignores location blockDebian 9 - nginx 忽略位置块
【发布时间】:2019-05-04 16:52:02
【问题描述】:

以下是我的nginx的mydomain.conf文件的内容。

server {
    server_name  www.mywebsite.com;

#the below works
add_header "this" "works";

    root /var/www/yii2app/web;
    index index.php;

    charset utf-8;
    access_log  off;
    error_log   off;

    location ~* \.(txt|js|json|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar|svg)$ {
        try_files $uri =404;
    }

    location /img {
        add_header Cache-Control "public, no-transform";
        add_header "hello" "word";
        expires max;
    }

    location ~ \.php$ {
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  /var/www/yii2app/web/$fastcgi_script_name;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        include        fastcgi_params;
    }

}

当我意识到我的位置块没有被 nginx 读取或接受时,我正在尝试配置缓存控制。

我通过添加一些额外的标题键值来测试这一点,例如:

add_header "this" "works";

add_header "hello" "word";

当我使用 curl 进行测试时,我可以看到 "this" "works",但看不到 /img location 块中的 "hello" "world"...

curl -I http://www.mywebsite.com/img/test.gif

我做错了什么?上面的配置是我目前的确切配置,除了网站地址和根路径。我已经注释掉了所有其他配置行。

【问题讨论】:

  • 请求由location ~* \.(txt|js|json|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar|svg)$ 块而不是location /img 块处理。
  • @RichardSmith 是的,我也注意到了这一点,但是在所有块中都放置了一个随机标题。有什么办法可以让 /img/ 块被考虑而不是另一个?我什至试图移动上面的 /img/ 无济于事。请建议我应该如何设置我的配置
  • ^~ 修饰符将赋予前缀位置比所有正则表达式位置更高的优先级。尝试location ^~ /img 并查看this document 了解详情。
  • 那行得通,我想你可以把它作为答案发布

标签: nginx debian config


【解决方案1】:

正则表达式位置块按顺序计算,优先于普通前缀位置块。

URI /img/foo.gif 将优先匹配location ~* \.(txt|js|json|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar|svg)$ 块而不是location /img 块,无论顺序如何。

您可以使用^~ 修饰符为前缀位置提供更高的优先级。

例如:

location ^~ /img { ... }

详情请见this document

或者,如果您不需要add_header 部分,您可以使用map with the expires directive

【讨论】:

    猜你喜欢
    • 2012-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-14
    • 2013-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多