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

Redirect to other server and domain if file not found

· 52CE 我爱测

I have migrated from Apache to Nginx so I want to set all rules in Nginx. Goal: Redirect a URL to another domain with the same filename if that file is not found on the requested server. Example If a user open https://www.example…

问题原文

原帖链接 · Shubham Panchal · CC BY-SA 4.0

I have migrated from Apache to Nginx so I want to set all rules in Nginx.

Goal: Redirect a URL to another domain with the same filename if that file is not found on the requested server.

Example

If a user open https://www.example.com/data/1.jpg then my server will try to find "1.jpg" in "data" dir. If that file is not found then redirect the user to backup server URL like https://www.example2.com/backup/1.jpg

Example in .htaccess

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule (.*) - [L]
RewriteRule (.*) https://example2.com/backup/$1 [L]

What I have tried

  1. Search for existing solutions but I didn't find any working solution.
  2. Try to convert apache config to Nginx config via converters but not working.

Some tried config but not working.

    location ~ /data/.* {
        if (-e $request_filename){
            rewrite ^ https://www.example2.com/backup/$1 last;
        } 
    }


    location ~ /data/.* {
        if (-e $request_filename){
            rewrite ^ https://www.example2.com/backup/$1 permanent;
        } 
    }


    location ~ /data/.* {
        try_files $uri https://www.example2.com/backup/$uri;
    }

已采纳解答

原帖链接 · Shubham Panchal · CC BY-SA 4.0

I got the solution after modifying @Rob answer.

set $v_filename nf;

location ~ ^/data/(.*)$ {
    try_files  $uri  @externalbackup;
    set $v_filename $1;
}

location @externalbackup {
     return 301  https://www.example2.com/backup/$v_filename ;
}

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

资料来源与适用范围

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

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

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