【问题标题】:Catching js|css in nginx location regexp在 nginx 位置正则表达式中捕获 js|css
【发布时间】:2020-02-02 17:18:25
【问题描述】:

请任何人解释我 - 为什么要求该网址 - http://localhost/static/css/style.css 返回404

这是我的 nginx.conf

的一部分
location ~ /static/(?<doctype>[js|css]+) {

  # root /usr/src/app/public/;

  if ($doctype = "css") {
    set $contnt_type "text/css";
  }
  if ($doctype = "js") {
    set $contnt_type "text/javascript";
  }

  expires 30d;
  add_header X_Cached 1;
  access_log off;

  add_header Cache-Control "public";
  add_header  Content-Type   $contnt_type;

   return 200  "$doctype";
}

谢谢

【问题讨论】:

  • 应该是$content_type
  • 您的正则表达式看起来不对。 [] 用于定义一个字符类。而且,$ 后面有字符,这是字符串锚点的结尾。也许这样的事情会起作用:location ~ ^/static/(?&lt;doctype&gt;js|css)/ { ... }
  • 您的正则表达式包含许多个错误。您想在http://localhost/static/css/style.css URL 上的$doctype 变量中捕获什么?你想退回什么?
  • @IvanShatsky 我想捕捉子路径的两个变体之一 - 它的“css”或“js”放在 request_uri 中的 /static/ 之后
  • 我了解到您希望在此位置处理 *.js 和 *.css 文件。当您收到http://localhost/static/css/style.css 请求时,您在$doctype 变量中取得了什么结果?

标签: regex nginx server


【解决方案1】:

事情没有你想的那么复杂。 在 NGINX 中根据文件扩展名更改 Content-Type 是一项微不足道的任务,您不需要专门的位置来实现。

只需根据文件扩展名编辑/etc/nginx/mime.types 与所需的Content-Type 标头值,例如:

types {
    text/html       html htm shtml;
    text/css        css;
    text/javascript js;     
    ...
}

不用说,编辑该文件将导致为整个 NGINX 安装指定的 Content-Type 值。在大多数情况下,这很好。

如果您确实想在 特定 位置更改 Content-Type(我真的不明白为什么,但为了完整起见),您也可以这样做,就像这样(假设您知道给定位置中所有可能的文件类型):

location /static/ {
  types { 
     text/css css;
     text/javascript js; 
     # be sure to add any extra file types you have below:
     # ...
  }   

  expires 30d;
  add_header X_Cached 1;
  access_log off;

  add_header Cache-Control "public";
}

【讨论】:

    【解决方案2】:

    您最好使用map 块而不是if 构造,if is evil

    map $doctype $contnt_type {
        js    "text/javascript";
        css   "text/css";
    }
    
    server
        ...
        location ~ ^/static/(?<doctype>js|css)/ {
            expires 30d;
            add_header X-Cached 1;
            access_log off;
            add_header Cache-Control "public";
            add_header Content-Type  $contnt_type;
        }
    }
    

    【讨论】:

    • 感谢您的支持。但是使用正则表达式的别名很奇怪)在行alias /usr/src/app/public/static/$doctype 的最后一个参数中,我只看到$doctype 的一个字母cj。这就是为什么最后我只使用root 指令。
    • 也许这是因为您的正则表达式中的错误,并且在将方括号替换为圆括号后已经更改?
    猜你喜欢
    • 2016-01-09
    • 1970-01-01
    • 2020-09-11
    • 2017-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-03
    相关资源
    最近更新 更多