1

我是 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 配置中结合重写和标头指令。

4

1 回答 1

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;
}

我可能有错别字或错误,我现在没有办法测试。让我知道

于 2013-11-05T11:54:36.390 回答