重定向到外部资产 nginx

重定向到外部资产 nginx

我的目标是拥有一个可以 proxy_pass 到其他服务器的 nginx。

Desired input

https://example.com/https://assets1.com/image.jpg?utm=whatever

Desired output
https://assets1.com/image.jpg?utm=whatever

这是我的位置块

server {

    index index.html index.htm index.nginx-debian.html;
    server_name example.com www.example.com;

    location ~/(.*) {
            if ($request_method = 'GET') {
                    add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Credentials' 'true';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
            add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User->
    }
    proxy_pass https://$1$is_args$args/;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header Host "www.example.com";
}
listen 80;
listen       [::]:442 ssl ipv6only=on;
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}

我得到的错误是:

2021/09/21 09:27:32 [错误] 8475#8475:*16上游端口无效 “https:/assets1.com/image.jpg?utm=whatever”,客户端:[IP],服务器:domain.com,请求:“GET /https://assets1.com/image.jpg?utm=whatever HTTP/1.1”,主机:“example.com”

答案1

您的原始请求 URL 包含协议前缀:https://example.com/https://assets1.com

您的location块捕获了第一之后的部分/,因此$1变成https://assets1.com

在您的proxy_pass语句中,您有,当变量扩展时https://$1$is_args$args它就会变成。https://https://assets1.com

nginx 尝试将其解析https://assets1.com为域:端口对,因此 URL 的域部分是,https而端口是空字符串。

为了解决这个问题,我建议以下配置:

location ~^/https://(.+)$ {
    proxy_pass https://$1$is_args$args;
    ...
}

这样,我们就可以将协议部分排除在 $1 之外,这样我们就有了一个正确的 URL。我还添加了开始和结束锚点,以使正则表达式更加健壮。

相关内容