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

Nginx redirect to another domain without trailing uri

· 52CE 我爱测

I am trying to get http://foo.mydomain.xyz/one/two/three.json by calling http://bar.mydomain.xyz/cat/one/two/three.json . I am using the following configuration: server { listen 80; listen [::]:80; server_name bar.mydomain.xyz; a…

问题原文

原帖链接 · Devil's Dream · CC BY-SA 4.0

I am trying to get http://foo.mydomain.xyz/one/two/three.json by calling http://bar.mydomain.xyz/cat/one/two/three.json. I am using the following configuration:

server {
        listen 80;
        listen [::]:80;
        server_name bar.mydomain.xyz;
        absolute_redirect off;

        location / {
          proxy_pass http://localhost:8080;
        }

        location /cat {
          rewrite ^(/cat) http://foo.mydomain.xyz$request_uri permanent;
        }
}
server {
        listen 80;
        listen [::]:80;
        server_name foo.mydomain.xyz;

        location / {
          proxy_pass http://localhost:7070;
        }
}

Using this configuration when I am calling: http://bar.mydomain.xyz/cat/ it is redirecting me to http://foo.mydomain.xyz/ successfully. But when I am calling http://bar.mydomain.xyz/cat/one/two/three.json it is returning http://foo.mydomain.xyz/cat/one/two/three.json. Notice the /cat is not removing from the url. How can I solve this?

已采纳解答

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

Your rewrite statement is changing the domain name but nothing else. The value of $request_uri is the original URI including the leading /cat part. You need to capture the latter part of the URI in the regular expression.

For example:

rewrite ^/cat/(.*)$ http://foo.example.com/$1 permanent;

Or maybe:

rewrite ^/cat(?:/(.*))?$ http://foo.example.com/$1 permanent;

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

资料来源与适用范围

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

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

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