Hamza Janzaib avatar
AboutResumeProjectsWorkBlogContact
Home/Blog/AWS, Deployment & DevOps/Creating and Configuring an AWS S3 Bucket for Static Hosting

Creating and Configuring an AWS S3 Bucket for Static Hosting

The S3 settings that matter for static hosting, and exactly why 403 errors happen.

By Hamza JanzaibNovember 28, 202611 min readIntermediate
Paste it into ChatGPT, Claude or any AI assistant.
  • aws
  • s3
  • bucket-policy
  • security
On this page ยท 17 sections
  • Pick a name and a region
  • Know the two endpoints
  • Layer 1: Block Public Access
  • Layer 2: Object ownership
  • Layer 3: The bucket policy
  • Restricting by IP or referer
  • Private bucket for CloudFront
  • Layer 4: Website hosting settings
  • Layer 5: CORS
  • Content types and cache headers
  • Protect your data and your wallet
  • Decoding the errors
  • A debugging checklist
  • Security considerations
  • Testing and validation
  • Best practices
  • Conclusion

Most "my S3 website does not work" problems are permission problems. S3 has several overlapping access controls (Block Public Access, bucket policies, object ownership, IAM policies, and two different endpoints), and they interact in ways that are easy to misread. This guide explains each setting that matters for static hosting, shows a correct configuration, and decodes the access errors you are likely to see.

If you want the end-to-end deployment steps, the companion guide on hosting a static website on S3 covers them. This article goes deeper on configuration and troubleshooting.

Pick a name and a region

Bucket names are global across all AWS accounts, so they must be unique. They must be 3 to 63 characters, lowercase letters, numbers, hyphens and dots, and cannot look like an IP address. Avoid dots in names if you plan to use HTTPS with the bucket directly, because dots interfere with the S3 wildcard certificate.

Pick the region based on where your users or your other resources are. For a CDN-fronted site the origin region matters less; for the S3 website endpoint it determines latency for everyone.

bash
aws s3api create-bucket --bucket my-site-example --region eu-west-1 \  --create-bucket-configuration LocationConstraint=eu-west-1

(For us-east-1, omit the location constraint.)

Know the two endpoints

This single distinction explains many surprises:

REST endpointWebsite endpoint
Addressbucket.s3.region.amazonaws.combucket.s3-website-region.amazonaws.com (separator varies by region)
ProtocolHTTP and HTTPSHTTP only
AccessSigned or public, honors IAM and bucket policiesPublic reads only
Index documentNoYes
Custom error document and redirectsNoYes
Works with CloudFront OACYesNo

Use the website endpoint for a simple public site. Use the REST endpoint behind CloudFront (with Origin Access Control) for a private, HTTPS site.

Layer 1: Block Public Access

Block Public Access is an account- and bucket-level safety net that overrides policies and ACLs. New buckets have all four settings enabled. The four settings:

SettingWhat it does
BlockPublicAclsRejects requests that add public ACLs
IgnorePublicAclsIgnores any existing public ACLs
BlockPublicPolicyRejects bucket policies that grant public access
RestrictPublicBucketsRestricts access to buckets with public policies to AWS services and authorized principals

For a public static website that uses a bucket policy, turn off the two policy-related settings and leave the ACL-related ones on:

bash
aws s3api put-public-access-block --bucket my-site-example \  --public-access-block-configuration \  BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=false,RestrictPublicBuckets=false

If your account has Block Public Access enabled at the account level, the bucket-level change is not enough; the account setting must allow it too. This is the usual reason a correct-looking policy is still rejected.

Layer 2: Object ownership

Older guidance involved public ACLs on every object. That is obsolete. New buckets use Bucket owner enforced, which disables ACLs entirely so the bucket owner owns every object and access is controlled only by policies. Keep it that way:

bash
aws s3api put-bucket-ownership-controls --bucket my-site-example \  --ownership-controls 'Rules=[{ObjectOwnership=BucketOwnerEnforced}]'

This also fixes a classic failure where objects uploaded by another account or tool were owned by the uploader and stayed private even though the bucket policy was public.

Layer 3: The bucket policy

A public-read website policy grants one action on one resource pattern:

json
{  "Version": "2012-10-17",  "Statement": [    {      "Sid": "PublicReadObjects",      "Effect": "Allow",      "Principal": "*",      "Action": "s3:GetObject",      "Resource": "arn:aws:s3:::my-site-example/*"    }  ]}

Details that matter:

  • Resource ends in /* because s3:GetObject applies to objects. Without /* the policy matches the bucket itself and grants nothing useful.
  • Do not grant s3:ListBucket publicly. It lets anyone list every file in your bucket.
  • Do not grant write actions to Principal: "*".

Restricting by IP or referer

An IP restriction is straightforward and reliable:

json
{  "Sid": "AllowOfficeIPOnly",  "Effect": "Allow",  "Principal": "*",  "Action": "s3:GetObject",  "Resource": "arn:aws:s3:::my-site-example/*",  "Condition": { "IpAddress": { "aws:SourceIp": "203.0.113.0/24" } }}

A condition on the Referer header is not real security, since the header is trivial to forge. Use it only to discourage casual hotlinking.

Private bucket for CloudFront

For production, the better policy trusts CloudFront instead of everyone, and Block Public Access stays fully on:

json
{  "Version": "2012-10-17",  "Statement": [    {      "Effect": "Allow",      "Principal": { "Service": "cloudfront.amazonaws.com" },      "Action": "s3:GetObject",      "Resource": "arn:aws:s3:::my-site-example/*",      "Condition": {        "StringEquals": {          "AWS:SourceArn": "arn:aws:cloudfront::123456789012:distribution/E1ABCDEXAMPLE"        }      }    }  ]}

Layer 4: Website hosting settings

bash
aws s3 website s3://my-site-example/ --index-document index.html --error-document error.html
  • The index document is served for requests to the root or a folder path.
  • The error document is served when an object is missing, with the error status code.
  • Redirect rules can send old paths to new URLs without any server code.

Layer 5: CORS

Browsers block cross-origin requests unless the response allows them. If a page on https://app.example.com loads fonts or JSON from your bucket with JavaScript, add CORS rules:

json
{  "CORSRules": [    {      "AllowedOrigins": ["https://app.example.com"],      "AllowedMethods": ["GET", "HEAD"],      "AllowedHeaders": ["*"],      "MaxAgeSeconds": 3600    }  ]}
bash
aws s3api put-bucket-cors --bucket my-site-example --cors-configuration file://cors.json

List specific origins instead of * when you can.

Content types and cache headers

S3 stores a Content-Type per object. A wrong type makes browsers download files instead of rendering them, or refuse to run scripts. aws s3 sync and aws s3 cp guess from the file extension; set it explicitly when you need to:

bash
aws s3 cp dist/index.html s3://my-site-example/index.html \  --content-type "text/html" --cache-control "no-cache"

Protect your data and your wallet

  • Versioning keeps previous versions of overwritten or deleted objects, which makes rollbacks and accident recovery possible.
  • Default encryption is applied to new objects with S3-managed keys, so you get encryption at rest without extra setup.
  • Lifecycle rules can expire old versions and abort incomplete multipart uploads, so storage does not grow without limit.
  • Access logging or CloudTrail data events help you audit who reads and writes.
bash
aws s3api put-bucket-versioning --bucket my-site-example \  --versioning-configuration Status=Enabled

Decoding the errors

ErrorWhat it usually meansFix
403 AccessDenied on a public siteBlock Public Access still on, missing GetObject policy, or object not owned by the bucket ownerCheck each layer above in order
403 for a missing page on a private bucketNo s3:ListBucket, so S3 hides whether the key existsAdd a CDN error mapping, or grant ListBucket to the CDN role
404 NoSuchKeyThe object really is missing, or the key has different case or a leading slashCompare aws s3 ls output with the URL
NoSuchBucketWrong name or region in the endpointVerify bucket name and region
NoSuchWebsiteConfigurationHosting not enabled, or you are using the REST endpoint where you need the website endpointEnable hosting and use the right URL
Browser downloads the fileWrong Content-TypeRe-upload with the right type
Access to fetch ... blocked by CORS policyMissing or too narrow CORS ruleAdd the origin and method
Policy has invalid resourceWrong ARN formatarn:aws:s3:::bucket for the bucket, arn:aws:s3:::bucket/* for objects

A debugging checklist

When a request fails, walk the layers in order:

  1. Endpoint: is this the website endpoint or the REST endpoint, and is that the right one for your setup?
  2. Account Block Public Access, then bucket Block Public Access.
  3. Bucket policy: correct principal, action and resource (/*)?
  4. Object ownership and existence: does the key exist with that exact name?
  5. Content type and CORS, if the request succeeds but the browser misbehaves.

Useful commands:

bash
aws s3api get-public-access-block --bucket my-site-exampleaws s3api get-bucket-policy --bucket my-site-exampleaws s3api get-bucket-website --bucket my-site-exampleaws s3api head-object --bucket my-site-example --key index.htmlaws s3 ls s3://my-site-example --recursive | head

IAM Access Analyzer for S3 can also flag buckets that are publicly accessible, which is a good safety check after any policy change.

Security considerations

  • Prefer a private bucket behind CloudFront for production.
  • Grant GetObject only; never ListBucket or write access to the public.
  • Keep Block Public Access on everywhere you do not need a public bucket, ideally enforced at the account level.
  • Do not put secrets or private data in a bucket that serves a website, and remember that everything in a public bucket is world-readable.
  • Use separate buckets for public assets and private data.

Testing and validation

After configuration, check that the site loads, that a missing page gives the intended result, that an object you did not intend to be public is not reachable, and that listing the bucket anonymously fails:

bash
curl -I http://my-site-example.s3-website-eu-west-1.amazonaws.com/curl -I http://my-site-example.s3-website-eu-west-1.amazonaws.com/does-not-existcurl -s https://my-site-example.s3.eu-west-1.amazonaws.com/ | head   # should be AccessDenied, not a file listing

Best practices

  • Understand which endpoint you use before touching permissions.
  • Use bucket policies, not ACLs, and keep Bucket owner enforced.
  • Grant the minimum: GetObject on /*.
  • Turn on versioning and review public access with Access Analyzer.
  • Use CloudFront for HTTPS and a private origin.

Conclusion

S3 permissions look confusing because several independent layers all have a veto. Once you walk them in a fixed order (endpoint, Block Public Access, policy, ownership, then metadata), almost every error becomes a one-line fix. Configure the minimum that your site needs, verify it from the outside, and prefer a private bucket with CloudFront when the site matters.

Frequently asked questions

+โˆ’Why does S3 return 403 instead of 404 for a missing file?

When the requester lacks s3:ListBucket permission, S3 returns 403 for missing keys so it does not reveal which objects exist. With s3:ListBucket granted, a missing key returns 404. This is why private buckets behind CloudFront often show 403 for unknown paths.

+โˆ’What do the four Block Public Access settings do?

BlockPublicAcls rejects new public ACLs, IgnorePublicAcls ignores existing public ACLs, BlockPublicPolicy rejects bucket policies that grant public access, and RestrictPublicBuckets limits access to buckets with public policies to AWS services and authorized users. A public website bucket needs the two policy-related ones turned off.

+โˆ’Are ACLs still needed for public access?

No. New buckets use the Bucket owner enforced object ownership setting, which disables ACLs. Use a bucket policy for access control instead of per-object ACLs.

+โˆ’Can I restrict an S3 website to certain IP addresses?

Yes, with a bucket policy condition on aws:SourceIp, but remember the bucket is then reachable only from those addresses. For most public sites the better design is a private bucket behind CloudFront, optionally with AWS WAF IP rules.

+โˆ’Why do my files download instead of displaying in the browser?

The object's Content-Type metadata is wrong, often binary/octet-stream. Re-upload with the correct content type, or use aws s3 sync which guesses types from file extensions.

+โˆ’When do I need a CORS configuration on the bucket?

When a browser page on another origin fetches files from your bucket with JavaScript, for example fonts, JSON or images drawn into a canvas. Add the allowed origins and methods in the bucket's CORS rules.

+โˆ’Is the S3 website endpoint secure enough for production?

The website endpoint only supports HTTP and requires a public bucket. For production use CloudFront with HTTPS in front of a private bucket, and keep the website endpoint only for simple or temporary setups.

Further reading

  • docs.aws.amazon.com/AmazonS3/latest/userguide/WebsiteHosting.html

Hamza Janzaib

Full-Stack Developer based in Karachi, Pakistan. Building web apps, APIs and cloud infrastructure. About me


Related articles

AWS, Deployment & DevOpsNovember 28, 202615 min readBeginner

Hosting a Static Website on AWS S3

Create a bucket, allow public reads, enable website hosting and deploy a build with one CLI command.

AWS, Deployment & DevOpsNovember 28, 202617 min readIntermediate

Configuring AWS CloudFront With S3 for Static Website Delivery

Keep the bucket private, serve through CloudFront, add HTTPS and a custom domain, and invalidate cleanly.

AWS, Deployment & DevOpsNovember 28, 202618 min readIntermediate

Deploying a Node.js Application on AWS EC2 From Scratch

The full path from an empty EC2 instance to a Node.js app behind Nginx and HTTPS, with troubleshooting.

Built by Hamza Janzaib

PrivacyTerms