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

nginx redirect static file request if 404

· 52CE 我爱测

I'm trying to redirect only static file requests from a particular directory prefix when they 404. I've tried using try_files and it may well work still but it hasn't for me so far. This is the scenario; Request is for https://ex…

问题原文

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

I'm trying to redirect only static file requests from a particular directory prefix when they 404.

I've tried using try_files and it may well work still but it hasn't for me so far.

This is the scenario;

Request is for https://example.com/forums/uploads/file.jpg File 404's Redirect to https://cdn.example.com/file.jpg

It's the change in path that I'm finding tricky.

I don't think it's possible, but a check for a non 404 on the CDN would be great also.

Solution (Based on accepted answer);

location ~* /forums/uploads {
    try_files $uri @rewriteimages;
}
location @rewriteimages {
    rewrite ^/forums/uploads(.*)$ https://cdn.example.com$1 redirect;
}

已采纳解答

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

You want to check for the existence of a local file and redirect the client to an external URL if that file does not exist.

You can use try_files to test for the existence of a local file, and rewrite to redirect the client to the external URL.

For example:

location /forums/uploads/
    try_files $uri @rewrite;
}
location @rewrite {
    rewrite ^/forums/uploads(.*)$ https://cdn.example.com$1 redirect;
}

See this document for more.

I don't think it's possible, but a check for a non 404 on the CDN would be great also.

Nginx takes no part in resolving the URL after it is redirected to the CDN.

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

资料来源与适用范围

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

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

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