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

nginx serve a different file name from local server if url/file does not exist

· 52CE 我爱测

Is there a way if file not exist to server another app-*.js file in other folder, example: Go to URL: http://www.example.com/assets/build/app/app-48fee50a26.js I am getting the following error message: [error] 17788#17788: *1 ope…

问题原文

原帖链接 · Berlin · CC BY-SA 3.0

Is there a way if file not exist to server another app-*.js file in other folder, example:

Go to URL: http://www.example.com/assets/build/app/app-48fee50a26.js

I am getting the following error message:

[error] 17788#17788: *1 open() "/var/app/assets/build/app/app-48fee50a26.js" failed (2: No such file or directory), client: , server: , request: "GET /assets/build/app/app-48fee50a26.js HTTP/1.1", host:""

I want to serve instead any other js file in the same folder /var/app/assets/build/app/, but the name of the other file can constantly change, for example app-62a5962b0a11.js. I was thinking about app\-(.*)\.js.

all the examples below does not work:

server {
        listen 80 default_server;
        root /var/app;

        location /assets/build/app/app\-(.*)\.js {
                try_files $uri $uri/ /assets/build/app/app\-(.*)\.js;
        }
}

server {
        listen 80 default_server;
        root /var/app;

        location /assets/build/app/app\-(.*)\.js {
                try_files $uri $uri/ /var/app/assets/build/app/app\-(.*)\.js;
        }
}


Also not working without regex to the location of the other file.

server {
        listen 80 default_server;
        root /var/app;

        location /assets/build/app/app\-(.*)\.js {
                try_files $uri $uri/ /var/app/assets/build/app/app-62a5962b0a11.js;
        }
}

server {
        listen 80 default_server;
        root /var/app;

        location /assets/build/app/app\-(.*)\.js {
                try_files $uri $uri/ /assets/build/app/app-62a5962b0a11.js;
        }
}

已采纳解答

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

Your location directive syntax is wrong. If you want to specify a regular expression, you must use the ~ or ~* modifier. See this document for details.

Also, you cannot expect nginx to look for a random file that matches a pattern. Which means that your last attempt is closest to a working solution. For example:

location ~ ^/assets/build/app/app-.+\.js$ {
    try_files $uri /assets/build/app/app-62a5962b0a11.js =404;
}

I have added the =404 as the default term to avoid generating a loop in the case that app-62a5962b0a11.js does not exist. But in general, app-62a5962b0a11.js must exist for proper operation. See this document for try_files syntax.

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

资料来源与适用范围

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

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

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