0

I am using S3 to store an xml file and use CloudFront to distribute this file. I want to use nginx proxy_pass to locate this file without change my domain name. such as www.mydomain.com/filename.xml The S3 url for that file is : https://s3-ap-southeast-2.amazonaws.com/bucketname/bucket-sub-name/filename.xml The CDN url is https://dev.example.com/filename.xml If I write nginx config like below, it works fine.

if($request_uri = "/filename.xml") {
    rewrite .* /bucketname/bucket-sub-name$request_uri break;
    proxy_pass https://s3-ap-southeast-2.amazonaws.com;
}

But If I changed nginx config like below, it gave me 502 bad gateway

if($request_uri = "/filename.xml"){
    proxy_pass https://dev.example.com$request_uri;
}

or

if($request_uri = "/filename.xml"){
    proxy_pass https://s3-ap-southeast-2.amazonaws.com/bucketname/bucket-sub-name$request_uri;
}

Is there any one could explain why the first one working and the second and third part not working? Is that because the CDN configuration has something wrong? Is that possiable that proxu_pass the url directly?

cccc
  • 23
  • 4

2 Answers2

2

you need

proxy_set_header Host "cdn domain" ;

to rewrite your nginx request host from nginx to cdn

Michael Hampton
  • 244,070
  • 43
  • 506
  • 972
jiangbo
  • 21
  • 2
0

Both if and rewrite directives are part of ngx_http_rewrite_module module and behavior you get, vary much depending on instructions surrounding them. It is a good idea to avoid if when you can. In your case, you probably can use nested locations...

Your second and third parts likely do not work because they specify exact URLs without rewriting and these URLs are wrong. When URLs are wrong, you can verify in error_log of Nginx, or also by using a debug version of nginx binary (nginx-debug) and switching error_log of Nginx to debug.

RLazar
  • 101
  • 3
  • Thank you for telling where I can get err_log when 502 bad request happened. and I found that if I used s3 domain directly, it tell me no resolve s3 domain, and I just added resolver 8.8.8.8 with google DNS before proxy_pass. But if I used AWS CDN url, the url still cannot be resolved. – cccc Jul 28 '17 at 02:21
  • If Nginx cannot resolve an URL that you assigned to CloudFront distribution, then I would start from verifying CDN settings. For example, use [Digwebinterface.com](http://www.digwebinterface.com/?hostnames=&type=ANY&onlyfirst=on&useresolver=8.8.4.4&ns=auth&nameservers=) – RLazar Jul 28 '17 at 11:54