DEV Community

Cao Duy Khanh
Cao Duy Khanh

Posted on

Nginx + Private S3

How can I view photos on private S3. Today I will show how we can do it with Nginx on AWS. We first need to set up something like below:

  • VPC(10.0.0.0/16) with a public subnet and a private subnet
  • VPC Endpoint for s3
  • A static web on ECS Fargate with Nginx
  • Private S3 Bucket which store images of application Alt Text

We will have a static web like below with an image loaded from the internet.
Alt Text

I have an image which store on S3. So I want to own static web will view that image.
Alt Text

Now I will go into setting specific sections.

(1) First we will need to update S3's bucket policy to only allow viewing of images from the vpc endpoint.

{
    "Version": "2008-10-17",
    "Id": "PolicyForCloudFrontPrivateContent",
    "Statement": [
        {
            "Sid": "Access-to-specific-VPCE-only",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::demo-static-s3/*",
            "Condition": {
                "StringEquals": {
                    "aws:sourceVpce": "vpce-0d92e50f230bc8070"
                }
            }
        }
    ]
}
Enter fullscreen mode Exit fullscreen mode

(2) Next we will configure Nginx to be able to view images from S3 as shown below.

location ~^/image/(.+)$ {
        resolver 10.0.0.2;
        proxy_pass http://s3-ap-southeast-1.amazonaws.com/demo-static-s3/image/$1; 
}
Enter fullscreen mode Exit fullscreen mode
  • resolver: IP address of the DNS server in your AWS VPC

I have VPC with CIDR range is 10.0.0.0/16. So IP address of the DNS server is 10.0.0.2 => Resolver is 10.0.0.2

10.0.0.0: Network address.
10.0.0.1: Reserved by AWS for the VPC router.
10.0.0.2: Reserved by AWS. The IP address of the DNS server is the base of the VPC network range plus two. For VPCs with multiple CIDR blocks, the IP address of the DNS server is located in the primary CIDR. We also reserve the base of each subnet range plus two for all CIDR blocks in the VPC. For more information, see Amazon DNS server.
10.0.0.3: Reserved by AWS for future use.
10.0.0.255: Network broadcast address. We do not support broadcast in a VPC, therefore we reserve this address.

Refer: https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Subnets.html

  • proxy_pass: s3 link

Format: http://s3-ap-southeast-1.amazonaws.com/[main_bucket]/[sub_bucket]/$1

(3) Next I will change the html to load an image from s3 instead of an online image.

<div class="container">
    <h1>Hey there</h1>
    <img src="https://cleandevs.com/image/668c1d479e27bb8750823655c83a6c9bd90263f9_hq.jpg"/>
  </div>
Enter fullscreen mode Exit fullscreen mode

(4) Finally, I will deploy to ECS Fargate. The result you will see is as below.
Alt Text

It is able to solution to view images from S3 without using CloudFront.

Discussion (0)