【问题标题】:Different location directives in ngnixnginx 中的不同位置指令
【发布时间】:2013-11-05 20:59:12
【问题描述】:

我是 ngnix 的新手,我不太了解 location 指令。我有一个具有以下配置的网站:

location / {
    rewrite ^(.*)$ /index.php last;
}

#assets

location /web/assets/ {
    rewrite ^(/web/assets/.*)$ $1 break;
}

location /web/assets/cache/ {
    if (!-f $request_filename) {
        rewrite ^/web/assets/cache/(.*)$ /web/assets/cache/index.php last;
    }
}

在网站中,所有请求都重定向到 index.php,但有一个我不想重定向的“资产”文件夹 (/web/assets/)。在此文件夹内有一个名为“缓存”的子文件夹。如果请求此子文件夹中的任何文件并且该文件不存在,则请求将重定向到创建该文件并将其保存在缓存中的 php 文件。这对于例如预处理的 css、js 等很有用,文件是在第一次需要时创建的。

此配置运行良好,但我想根据 html5 样板建议将一些标头发送到资产文件,例如静态内容的过期规则 (https://github.com/h5bp/server-configs-nginx/blob/master/conf/expires.conf),以及当我添加这些指令时:

location ~* \.(?:jpg|jpeg|gif|png|ico|cur|gz|svg|svgz|mp4|ogg|ogv|webm|htc)$ {
  expires 1M;
  access_log off;
  add_header Cache-Control "public";
}

# CSS and Javascript
location ~* \.(?:css|js)$ {
  expires 1y;
  access_log off;
  add_header Cache-Control "public";
}

之前的重定向不起作用。我做客是因为 nginx 不会执行所有匹配的位置,而只会执行第一个。我的问题是如何在 ngnix 配置中结合 rewrite 和 header 指令。

【问题讨论】:

    标签: php nginx


    【解决方案1】:

    每个请求只能由一个位置块处理。此外,if 的使用也不是一个好习惯。 try_files 可以更有效率。此外,您有一个重写规则,可以重写为相同的 uri(完全没用)。

    请允许我将您的 conf 重写为我认为更有效地满足您的需求,如果我有什么问题请告诉我

    #this is just fine as it was
    location / {
      rewrite ^(.*)$ /index.php last;
    }
    
    #web assets should be served directly
    location /web/assets/ {
      try_files $uri $uri/ @mycache;
    }
    
    #this is the mycache location, called when assets are not found
    location @mycache {
      expires 1y;
      access_log on;
      add_header Cache-Control "public";
      rewrite ^/web/assets/(.*)$ /web/assets/cache/index.php last;
    }
    
    #some specific files in the web/assets directory. if this matches, it is preferred over the location web/assets because it is more specific
    location ~* /web/assets/.*\.(jpg|jpeg|gif|png|ico|cur|gz|svg|svgz|mp4|ogg|ogv|webm|htc)$ {
      expires 1M;
      access_log off;
      add_header Cache-Control "public";
      try_files $uri $uri/ @mycache;
    }
    
    # CSS and Javascript
    location ~* /web/assets/.*\.(css|js)$ {
      expires 1y;
      access_log off;
      add_header Cache-Control "public";
      try_files $uri $uri/ @mycache;
    }
    

    我可能有错别字或错误,我现在没有办法测试。告诉我

    【讨论】:

    • 谢谢@foibs,我已经更改了配置文件,添加了您的代码,看起来一切正常。我会做更多的测试,我会告诉你的。
    • 你好。您的代码存在一些问题。 (在这里测试过:wok.io)。
    • 抱歉,我在上一条评论中按了“回车”。我希望仅当 /web/assets/cache 中不存在该文件时才进行重定向,而不是针对 /web/assets 中的所有文件。现在,不会加载未重定向的文件(从 /cache 加载,例如图像)。我还可以看到过期标头未发送
    • 我已经编辑了我的 conf。我在页面中看到很多 404。正确的目录是web/assets 还是wok/assets?此外,一些访问和错误日​​志会有所帮助
    • 啊,好的,正确的目录是 wok,而不是 web。我要做出改变。
    猜你喜欢
    • 1970-01-01
    • 2012-11-09
    • 1970-01-01
    • 2020-03-26
    • 1970-01-01
    • 2012-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多