问题原文
原帖链接 · Harsh · CC BY-SA 4.0
I want to set up a temporary redirect to another domain but I want to keep the path very similar.
Here's an example:
Request URL: https://api.mydomain.com/uploads/default/logo.png
Rewritten URL should be: https://cdn.mydomain.com/default/logo.png
I have set the rule like this but it isn't working:
{
server api.mydomain.com
location /uploads/(.*)$ {
rewrite ^ $scheme://cdn.mydomain.com/$1 redirect;
}
}
已采纳解答
原帖链接 · Ivan Shatsky · CC BY-SA 4.0
Some explanations why your rewrite solution was not working. rewrite directive treats its first parameter as regex. You are using ^ as regex (a very common approach to match any string), and after regex matching $1 variable has an empty value because ^ regex pattern doesn't have any capture groups. So it comes that the previous $1 variable value get lost. In opposite return directive doesn't treat any parameter as regex and $1 variable value doesn't get altered.
What can you do to prevent loss of $1 variable value? Here are another two possible solutions:
- Use named capture group in
locationdirective:{ server api.mydomain.com location /uploads/(?<suffix>.*) { rewrite ^ $scheme://cdn.mydomain.com/$suffix redirect; } ... } - Use
rewritedirective in theservercontext instead oflocationone:{ server api.mydomain.com rewrite ^/uploads/(.*) $scheme://cdn.mydomain.com/$1 redirect; ... }
Sometimes using numeric capture groups leads to errors that are very hard to track, see this question/answer for example.
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
