Using an Amazon S3 Bucket as a Static Web Host

This Python example shows you how to set up an Amazon S3 bucket as a static web host. The Scenario

In this example, Python code is used to configure any of your buckets to act as a static web host. The code uses the AWS SDK for Python to configure a selected Amazon S3 bucket using these methods of the Amazon S3 client class:

For more information about using an Amazon S3 bucket as a static web host, see Hosting a Static Website on Amazon S3 in the Amazon Simple Storage Service Developer Guide.

All the example code for the Amazon Web Services (AWS) SDK for Python is available here on GitHub.

Prerequisite Tasks

To set up and run this example, you must first complete this task:

  • Configure your AWS credentials, as described in Quickstart.

Get the Current Bucket Website Configuration

The example below shows how to:

Example

import boto3

# Create an S3 client
s3 = boto3.client('s3')

# Call to S3 to retrieve the policy for the given bucket
result = s3.get_bucket_website(Bucket='my-bucket')

Set a Bucket Website Configuration

The example below shows how to:

Example

import boto3

# Create an S3 client
s3 = boto3.client('s3')

# Create the configuration for the website
website_configuration = {
    'ErrorDocument': {'Key': 'error.html'},
    'IndexDocument': {'Suffix': 'index.html'},
}

# Set the new policy on the selected bucket
s3.put_bucket_website(
    Bucket='my-bucket',
    WebsiteConfiguration=website_configuration
)

Delete a Bucket Website Configuration

The example below shows how to:

Example

import boto3

# Create an S3 client
s3 = boto3.client('s3')

# Call S3 to delete the website policy for the given bucket
s3.delete_bucket_website(Bucket='my-bucket')