大网数据广告活动
服务器运维问答

How to build a nginx location wildcard to match /sub/test.jpg but not /test.jpg

· 52CE 我爱测

I have a location rule in nginx which tries to catch any js, css and jpg files: server{ listen 80; server_name example.com location ~* \.(js|css|jpg)$ { root /srv/html; } } This works fine. When I hit http://example.com/test.jpg …

问题原文

原帖链接 · v25 · CC BY-SA 4.0

I have a location rule in nginx which tries to catch any js, css and jpg files:

server{
    listen 80;
    server_name example.com

    location ~* \.(js|css|jpg)$ {
        root /srv/html;
    }
}

This works fine. When I hit http://example.com/test.jpg it loads my image, so the permissions are correct.

However I want to change this so that only items under http://example.com/sub/ are matched.

So, based on this answer I changed the location to:

location ~* ^/sub/\.(js|css|jpg)$ {
    root /srv/html;
}

but this location doesn't appear to match http://example.com/sub/test.jpg

I also tried with:

location ~* ^/sub/.+\.(js|css|jpg)$ {
    root /srv/html;
}

which matches the location block, but looks for the file in /srv/html/sub/ according to my error log:

open() "/srv/html/sub/test.jpg" failed (2: No such file or directory)

What's the correct way to write this so that I can:

  • access http://example.com/sub/test.jpg
  • nginx retreives the file from /srv/html/test.jpg (which also works for *.jpg, *.css and *.js)
  • the rule doesn't match http://example.com/test.jpg

已采纳解答

原帖链接 · Richard Smith · CC BY-SA 4.0

You have a file located at /srv/html/test.jpg and you want to access it using the URI /sub/test.jpg.

This requires the alias directive as the path to the file cannot be constructed by simply concatenating the document root with the URI.

For example:

location /sub/ {
    alias /srv/html/;
}

The trailing / on both the location and alias values is significant. Either both have a trailing / or neither have a trailing /.


Using the alias directive with a regular expression location block, requires you to capture the remainder of the URI and construct the path to the file in the alias statement.

For example:

location ~* ^/sub(/.+\.(js|css|jpg))$ {
    alias /srv/html$1;
}

The order of the regular expression location blocks is significant. The regular expressions are evaluated in order, so a more specific regular expression should be placed before a less specific regular expression.

See this document for the alias directive, and this document for the location directive.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2019-01-17)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。