问题原文
原帖链接 · 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
- Search for existing solutions but I didn't find any working solution.
- 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 ;
}
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
