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

Nginx: Rewrite while preserving the path

· 52CE 我爱测

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…

问题原文

原帖链接 · 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 location directive:
    {
    
        server api.mydomain.com
    
        location /uploads/(?<suffix>.*) {
            rewrite ^ $scheme://cdn.mydomain.com/$suffix redirect;
        }
    
        ...
    
    }
    
  • Use rewrite directive in the server context instead of location one:
    {
    
        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.

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

资料来源与适用范围

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

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

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