Dean Christian Armada
Dean Christian Armada

Reputation: 7364

Nginx proxy pass with rewrite and regex

Can Nginx rewrite a URL then use it as a proxy pass?

For example when I visit http://localhost/downloads/example-com/pc.html it should proxy to http://example.com/pc.html

Basically, I want to use my domain to download a file from another website that is why I am doing this

Upvotes: 2

Views: 8574

Answers (1)

Bhavin Hirpara
Bhavin Hirpara

Reputation: 356

Yes you can rewrite url and proxy_pass to rewritten url. But as per what you want to achieve, this simple solution should also work :

location ~ /example-com/(.*)$ {
    proxy_pass http://example.com/$1;
}

if you want you achieve it by rewriting only then you can try following one :

location ~ /example-com/ {
   rewrite  /example-com/(.*) /$1 break;
   proxy_pass http://example.com;
}

UPDATE :

pass another website url as query param like below :

http://yourdomain/downloads/data?data_url=example.com/pc.html

and change your nginx configuration as below.

location ~ /downloads/data {
    set $data_url $arg_data_url;
    proxy_pass http://$data_url;
}

after this configuration change you might get resolver issue as we are passing hostname in proxy_pass at runtime. To solve resolver issue you can follow this link : https://runkiss.blogspot.com/2020/01/using-nginx-authrequest-to-proxy-to.html

Upvotes: 2

Related Questions