nginx中的通配符请求/位置?

时间:2013-05-10 09:55:44

标签: nginx request rewrite wildcard config

我有一个脚本,每次部署我的网站时都会增加全局修订号。然后将此数字映射到加载CSS,JavaScript和sprite资产的HTML中。这被用作缓存破坏策略。

例如<link rel="stylesheet" href="/css/screen_r123.css" type="text/css" />

在Apache中,我会将这些递增的URL重写为实际的资产,如下所示:

RewriteRule ^css/screen_r(.*).css$ /css/screen_min.css [L]

我如何在nginx 中做同样的事情?我不确定在哪里放置正则表达式匹配逻辑。

注意:我不想将查询?r=123附加到URI的末尾,因为将查询传递给静态资产感觉不正确,而且我在Varnish代理后面在缓存哈希中不包含查询


以下是我网站的当前nginx配置文件:

server {
  listen 8080;
  server_name domain.com www.domain.com
  port_in_redirect off;

  root /usr/share/nginx/mydomain.com/public;
  index index.html index.php;

  #set long expiry for assets
  location ~* \.(ico|css|js|gif|jpe?g|png)(\?[0-9]+)?$ {
    expires max;
    log_not_found off;
  }

  location / {
    #FOLLOWING LINE DOES NOT WORK AS INTENDED
    rewrite ^/css/screen_r(.*).css$ /css/screen.css last;

    # Check if a file or directory index file exists, else route it to index.php.
    try_files $uri $uri/ /index.php;
  }

  location ~* \.php$ {     
    fastcgi_pass   unix:/tmp/php5-fpm.sock;
    fastcgi_index  index.php;
    fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include        fastcgi_params;
    fastcgi_param APPLICATION_ENV "production";
    fastcgi_split_path_info ^(.+.php)(.*)$;
  }

  add_header "X-UA-Compatible" "IE=Edge,chrome=1";
  add_header Cache-Control "public max-age=60";
}

1 个答案:

答案 0 :(得分:0)

解决。重写指令需要在任何location块之外。

这有效:

server {
  listen 8080;
  server_name domain.com www.domain.com;
  port_in_redirect off;

  rewrite ^/css/screen_r(.*).css$ /css/screen.css last;
  ...