重新導向到外部資產 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。我還添加了開始和結束錨點以使正則表達式更加健壯。

相關內容