Hosting a Static Website

This tutorial describes how to configure a Cloud Storage bucket to host a static website. Static web pages can contain client-side technologies such as HTML, CSS, and JavaScript. For more information on static web pages, such as examples, tips and troubleshooting, see the Static Website page.

This tutorial also applies to hosting static assets for a dynamic website.

Objectives

In this tutorial you will:

  • Point your domain to Cloud Storage.
  • Create a bucket that is linked to your domain.
  • Upload and share your site's files.
  • Test the website.

Costs

This tutorial uses the following billable component of Cloud Platform:

  • Hosting a Static Website

See the Monitoring your storage charges tip for details on what charges may be incurred when hosting a static website, and see the Pricing page for details on Cloud Storage costs.

Before you begin

  1. Faça login na conta do Google.

    Se você ainda não tiver uma, inscreva-se para ter uma nova.

  2. Select or create a Cloud Platform project.

    Go to the Manage resources page

  3. Ative o faturamento do projeto.

    Ativar faturamento

  4. Have a domain that you own or manage. If you don't have an existing domain, there are many services through which can you can register a new domain, such as Google Domains.

    This tutorial uses the domain example.com.

  5. Verify that you own or manage the domain you will be using. To demonstrate that you are an owner or manager of a domain, use one of the Google Webmaster Central verification processes. Make sure you are verifying the domain, for example, example.com, and not a site on the domain, such as www.example.com.

    Note: If you own the domain you are associating to a bucket, you might have already performed this step in the past. If you purchased your domain through Google Domains, verification is automatic.

    For more information, see Domain-Named Bucket Verification.

Creating a CNAME alias

Create a CNAME alias that points to c.storage.googleapis.com..

A CNAME alias is a DNS record that lets you use a URL from your own domain to access resources, such as a bucket and objects, in Cloud Storage using your custom domain URL. For example, for www.example.com, the CNAME record might contain the following information:

NAME                  TYPE     DATA
www.example.com       CNAME    c.storage.googleapis.com.

Your domain registration service should have a way that you can administer your domain, including adding a CNAME resource record. For example, if you use Google Domains, instructions for adding a resource record can be found on the Google Domains Help page, in the Resource records drop-down section.

For more information about CNAME redirects, see URI for CNAME aliasing.

Creating a bucket

Create a bucket whose name matches the CNAME you created for your domain.

For example, if you added a CNAME record pointing www.example.com to c.storage.googleapis.com., then create a bucket with the name "www.example.com".

To create a bucket:

Console

  1. Open the Cloud Storage browser in the Google Cloud Platform Console.
    Open the Cloud Storage browser
  2. Click Create bucket.
  3. In the Create bucket dialog, specify:
    • The Name of your bucket.
    • The Storage class for your bucket: Multi-Regional.
    • The Location of your bucket: United States.

    New Multi-Regional Storage bucket.

  4. Click Create.
  5. If successful, you are taken to the bucket's page with the text "There are no objects in this bucket."

gsutil

Use the gsutil mb command:

gsutil mb gs://www.example.com

If successful, the command returns:

Creating gs://www.example.com/...

Client Libraries

C#

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

private void CreateBucket(string bucketName)
{
    var storage = StorageClient.Create();
    storage.CreateBucket(s_projectId, bucketName);
    Console.WriteLine($"Created {bucketName}.");
}

Go

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

bucket := client.Bucket(bucketName)
if err := bucket.Create(ctx, projectID, &storage.BucketAttrs{
	StorageClass: "COLDLINE",
	Location:     "asia",
}); err != nil {
	return err
}

Java

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

Bucket bucket = storage.create(BucketInfo.newBuilder(bucketName)
    // See here for possible values: http://g.co/cloud/storage/docs/storage-classes
    .setStorageClass(StorageClass.COLDLINE)
    // Possible values: http://g.co/cloud/storage/docs/bucket-locations#location-mr
    .setLocation("asia")
    .build());

Node.js

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

// Imports the Google Cloud client library
const Storage = require('@google-cloud/storage');

// The name of the bucket to create, e.g. "my-bucket"
// const bucketName = "my-bucket";

// Instantiates a client
const storage = Storage();

// Creates a new bucket
storage
  .createBucket(bucketName)
  .then(() => {
    console.log(`Bucket ${bucketName} created.`);
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

PHP

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

use Google\Cloud\Storage\StorageClient;

/**
 * Create a Cloud Storage Bucket.
 *
 * @param string $bucketName name of the bucket to create.
 * @param string $options options for the new bucket.
 *
 * @return Google\Cloud\Storage\Bucket the newly created bucket.
 */
function create_bucket($bucketName, $options = [])
{
    $storage = new StorageClient();
    $bucket = $storage->createBucket($bucketName, $options);
    printf('Bucket created: %s' . PHP_EOL, $bucket->name());
}

Python

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

def create_bucket(bucket_name):
    """Creates a new bucket."""
    storage_client = storage.Client()
    bucket = storage_client.create_bucket(bucket_name)
    print('Bucket {} created'.format(bucket.name))

Ruby

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

# project_id    = "Your Google Cloud project ID"
# bucket_name   = "Name of Google Cloud Storage bucket to create"

require "google/cloud/storage"

storage = Google::Cloud::Storage.new project: project_id
bucket  = storage.create_bucket bucket_name,
                                location:      "ASIA",
                                storage_class: "COLDLINE"

puts "Created bucket #{bucket.name}"

REST APIS

JSON API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Create a .json file that assigns the name property your website name:
  3. {
     "name": "www.example.com"
    }
  4. Use cURL to call the JSON API. For www.example.com:
    curl -X POST --data-binary @website-bucket-name.json \
         -H "Authorization: Bearer ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg" \
         -H "Content-Type: application/json" \
         "https://www.googleapis.com/storage/v1/b?project=my-static-website"

XML API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Use cURL to call the XML API to create a bucket with your website name. For www.example.com:
    curl -X PUT \
         -H "Authorization: Bearer ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg" \
         -H "x-goog-project-id: my-static-website" \
         "https://storage.googleapis.com/www.example.com"

Uploading your site's files

To add to your bucket the files you want your website to serve:

Console

  1. Open the Cloud Storage browser in the Google Cloud Platform Console.
    Open the Cloud Storage browser
  2. In the list of buckets, click on the bucket you created.
  3. Click Upload files.
  4. In the file dialog, browse to the desired file and select it.

After the upload completes, you should see the file name, size, type, and last modified date in the bucket.

For example a bucket with two files index.html and 404.html appears in the Cloud Platform Console as:

Bucket website example.
Example of a bucket configured as a website.

gsutil

Use the gsutil cp command to copy files to your bucket. For example, to copy the file index.html from its current location Desktop:

gsutil cp Desktop/index.html gs://www.example.com

If successful, the command returns:

Copying file://Desktop/index.html [Content-Type=text/html]...
Uploading   gs://www.example.com/index.html:       0 B/2.58 KiB
Uploading   gs://www.example.com/index.html:       2.58 KiB/2.58 KiB

Client Libraries

C#

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

private void UploadFile(string bucketName, string localPath,
    string objectName = null)
{
    var storage = StorageClient.Create();
    using (var f = File.OpenRead(localPath))
    {
        objectName = objectName ?? Path.GetFileName(localPath);
        storage.UploadObject(bucketName, objectName, null, f);
        Console.WriteLine($"Uploaded {objectName}.");
    }
}

Go

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

f, err := os.Open("notes.txt")
if err != nil {
	return err
}
defer f.Close()

wc := client.Bucket(bucket).Object(object).NewWriter(ctx)
if _, err = io.Copy(wc, f); err != nil {
	return err
}
if err := wc.Close(); err != nil {
	return err
}

Java

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

InputStream content = new ByteArrayInputStream("Hello, World!".getBytes(UTF_8));
Blob blob = bucket.create(blobName, content, "text/plain");

Node.js

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

// Imports the Google Cloud client library
const Storage = require('@google-cloud/storage');

// The name of the bucket to access, e.g. "my-bucket"
// const bucketName = "my-bucket";

// The name of the local file to upload, e.g. "./local/path/to/file.txt"
// const filename = "./local/path/to/file.txt";

// Instantiates a client
const storage = Storage();

// Uploads a local file to the bucket
storage
  .bucket(bucketName)
  .upload(filename)
  .then(() => {
    console.log(`${filename} uploaded to ${bucketName}.`);
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

PHP

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

use Google\Cloud\Storage\StorageClient;

/**
 * Upload a file.
 *
 * @param string $bucketName the name of your Google Cloud bucket.
 * @param string $objectName the name of the object.
 * @param string $source the path to the file to upload.
 *
 * @return Psr\Http\Message\StreamInterface
 */
function upload_object($bucketName, $objectName, $source)
{
    $storage = new StorageClient();
    $file = fopen($source, 'r');
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->upload($file, [
        'name' => $objectName
    ]);
    printf('Uploaded %s to gs://%s/%s' . PHP_EOL, basename($source), $bucketName, $objectName);
}

Python

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

def upload_blob(bucket_name, source_file_name, destination_blob_name):
    """Uploads a file to the bucket."""
    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucket_name)
    blob = bucket.blob(destination_blob_name)

    blob.upload_from_filename(source_file_name)

    print('File {} uploaded to {}.'.format(
        source_file_name,
        destination_blob_name))

Ruby

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

# project_id        = "Your Google Cloud project ID"
# bucket_name       = "Your Google Cloud Storage bucket name"
# local_file_path   = "Path to local file to upload"
# storage_file_path = "Path to store the file in Google Cloud Storage"

require "google/cloud/storage"

storage = Google::Cloud::Storage.new project: project_id
bucket  = storage.bucket bucket_name

file = bucket.create_file local_file_path, storage_file_path

puts "Uploaded #{file.name}"

REST APIS

JSON API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Add the file data to the request body.
  3. Use cURL to call the JSON API with a POST Object request. For the index page of www.example.com:
    curl -X POST --data-binary @index.html \
            -H "Content-Type: text/html" \
            -H "Authorization: Bearer ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg" \
            "https://www.googleapis.com/upload/storage/v1/b/www.example.com/o?uploadType=media&name=index.html"

See Performing a Simple Upload for more information about uploading objects with the JSON API.

XML API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Add the object's data to the request body.
  3. Use cURL to call the XML API with a PUT Object request. For the index page of www.example.com:
    curl -X PUT --data-binary @index.html \
            -H "Authorization: Bearer ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg" \
            -H "Content-Type: text/html" \
            "https://storage.googleapis.com/www.example.com/index.html"

Sharing your files

To share publicly the files that you want to serve:

Console

  1. Open the Cloud Storage browser in the Google Cloud Platform Console.
    Open the Cloud Storage browser
  2. In the list of buckets, click on the bucket that contains the objects you uploaded.
  3. For each object you want to share publicly, click the checkbox in the Share publicly column.

If successful, a link titled Public link appears next to the checkbox.

gsutil

Use the gsutil acl ch command to grant all users read permission for each of the files stored in your bucket that you plan to serve. For example:

gsutil acl ch -u AllUsers:R gs://www.example.com/index.html

If successful, the command returns:

Updated ACL on gs://www.example.com/index.html

Client Libraries

C#

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

private void MakePublic(string bucketName, string objectName)
{
    var storage = StorageClient.Create();
    var storageObject = storage.GetObject(bucketName, objectName);
    storageObject.Acl = storageObject.Acl ?? new List<ObjectAccessControl>();
    storage.UpdateObject(storageObject, new UpdateObjectOptions
    {
        PredefinedAcl = PredefinedObjectAcl.PublicRead
    });
    Console.WriteLine(objectName + " is now public and can be fetched from " +
        storageObject.MediaLink);
}

Go

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

acl := client.Bucket(bucket).Object(object).ACL()
if err := acl.Set(ctx, storage.AllUsers, storage.RoleReader); err != nil {
	return err
}

Java

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

BlobId blobId = BlobId.of(bucketName, blobName, blobGeneration);
Acl acl = storage.createAcl(blobId, Acl.of(User.ofAllUsers(), Role.READER));

Node.js

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

// Imports the Google Cloud client library
const Storage = require('@google-cloud/storage');

// The name of the bucket to access, e.g. "my-bucket"
// const bucketName = "my-bucket";

// The name of the file to make public, e.g. "file.txt"
// const filename = "file.txt";

// Instantiates a client
const storage = Storage();

// Makes the file public
storage
  .bucket(bucketName)
  .file(filename)
  .makePublic()
  .then(() => {
    console.log(`gs://${bucketName}/${filename} is now public.`);
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

PHP

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

use Google\Cloud\Storage\StorageClient;

/**
 * Make an object publically accessible.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 * @param string $objectName the name of your Cloud Storage object.
 *
 * @return void
 */
function make_public($bucketName, $objectName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $object->update(['acl' => []], ['predefinedAcl' => 'PUBLICREAD']);
    printf('gs://%s/%s is now public' . PHP_EOL, $bucketName, $objectName);
}

Python

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

def make_blob_public(bucket_name, blob_name):
    """Makes a blob publicly accessible."""
    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucket_name)
    blob = bucket.blob(blob_name)

    blob.make_public()

    print('Blob {} is publicly accessible at {}'.format(
        blob.name, blob.public_url))

Ruby

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Your Google Cloud Storage bucket name"
# file_name   = "Name of file in Google Cloud Storage to make public"

require "google/cloud/storage"

storage = Google::Cloud::Storage.new project: project_id
bucket  = storage.bucket bucket_name
file    = bucket.file file_name

file.acl.public!

puts "#{file.name} is publicly accessible at #{file.public_url}"

REST APIS

JSON API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Create a .json file that contains the following information:
  3. {
      "entity": "allUsers",
      "role": "READER"
    }
  4. Use cURL to call the JSON API with an Insert ACL request. For the index page of www.example.com:
    curl -X POST --data-binary @public-read.json \
            -H "Authorization: Bearer ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg" \
            -H "Content-type: application/json" \
            "https://www.googleapis.com/storage/v1/b/www.example.com/o/index.html/acl"

XML API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Create a .xml file that contains the following information:
  3. <AccessControlList>
      <Entries>
        <Entry>
          <Scope type="AllUsers"/>
          <Permission>READ</Permission>
        </Entry>
      </Entries>
    </AccessControlList>
    
  4. Use cURL to call the XML API with an Set Object ACL request. For the index page of www.example.com:
    curl -X PUT --data-binary @[XML_FILE_NAME].xml \
            -H "Authorization: Bearer ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg" \
            "https://storage.googleapis.com/www.example.com/index.html?acl"

Optional: Assigning index and error pages

From the files you shared publicly, you can assign an index page suffix and a custom error page, though doing either is optional.

An index page (also called a webserver directory index) is the file returned to visitors to your static site who request a "directory". If the top level site, such as http://www.example.com, is requested, or a missing page is requested, e.g., http://www.example.com/directory, the service attempts to return an index page. If you haven't assigned an index page suffix, or if the "directory" doesn't have an associated index page, Cloud Storage returns an error page. The property that controls which file acts as the index page is MainPageSuffix.

For example, if the MainPageSuffix is index.html, Cloud Storage attempts to return the object www.example.com/index.html when a user requests http://www.example.com. Similarly, if there is no object www.example.com/directory, then Cloud Storage attempts to return the object www.example.com/directory/index.html when a user requests http://www.example.com/directory. If there is no such object, Cloud Storage returns an error page.

The error page is the file returned to visitors of your static site who request a URL that does not correspond to an existing file. If you have assigned an index page, the error page is returned when the requested URL does not correspond to an appropriate index object. The http response code is 404 when returning the error page. The property that controls which file acts as the error page is NotFoundPage. If you don't set NotFoundPage, users receive a generic error page.

In the following sample, an index page suffix is set to index.html and a custom error page is set to 404.html:

Console

  1. Open the Cloud Storage browser in the Google Cloud Platform Console.
    Open the Cloud Storage browser
  2. In the list of buckets, find the bucket you created.
  3. Click the more actions icon More actions icon. next to the bucket and select Edit website configuration.
  4. In the Configure website dialog, specify the Main Page and the 404 (Not Found) Page.
  5. Click Save.

gsutil

Using the gsutil tool:

The following command sets the MainPageSuffix property to index.html and the NotFoundPage property to 404.html for the bucket www.example.com.

gsutil web set -m index.html -e 404.html gs://www.example.com

If successful, the command returns:

Setting website config on gs://www.example.com/...

REST APIS

JSON API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Create a .json file that sets the mainPageSuffix and notFoundPage properties in a website object to the desired pages:
    {
      "website":{
        "mainPageSuffix": "index.html",
        "notFoundPage": "404.html"
      }
    }
  3. Use cURL to call the JSON API with a PATCH Bucket request. For www.example.com:
    curl -X PATCH --data-binary @web-config.json \
         -H "Authorization: Bearer ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg" \
         -H "Content-Type: application/json" \
         "https://www.googleapis.com/storage/v1/b/www.example.com"

XML API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Create a .xml file that sets the MainPageSuffix and NotFoundPage elements in a WebsiteConfiguration element to the desired pages:
    <WebsiteConfiguration>
      <MainPageSuffix>index.html</MainPageSuffix>
      <NotFoundPage>404.html</NotFoundPage>
    </WebsiteConfiguration>
  3. Use cURL to call the XML API, with a PUT Bucket request and websiteConfig query string parameter. For www.example.com:
    curl -X PUT --data-binary @web-config.xml \
            -H "Authorization: Bearer ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg" \
            https://storage.googleapis.com/www.example.com?websiteConfig

Testing the website

Test that content is served from the bucket by requesting the domain name in a browser, either with a path to an object, or if you set the MainPageSuffix property, with just the domain name.

Cleaning up

After you've finished the Hosting a Static Website tutorial, you can clean up the resources you created on Google Cloud Platform so you won't be billed for them in the future. The following sections describe how to delete or turn off these resources.

Deleting the project

The easiest way to eliminate billing is to delete the project you created for the tutorial.

To delete the project:

  1. In the Cloud Platform Console, go to the Projects page.

    Go to the Projects page

  2. In the project list, select the project you want to delete and click Delete project. After selecting the checkbox next to the project name, click
      Delete project
  3. In the dialog, type the project ID, and then click Shut down to delete the project.

Deleting the bucket

If you do not want to delete the entire project, delete the bucket that you used for hosting your website:

Console

  1. Open the Cloud Storage browser in the Google Cloud Platform Console.
    Open the Cloud Storage browser
  2. Select the checkbox next to the bucket that you created.
  3. Click Delete.
  4. In the overlay that appears, click Delete to permanently delete the bucket and its contents.

gsutil

Use the gsutil rm command with the -r flag to delete the bucket and the contents inside of it:

gsutil rm -r gs://www.example.com

What's next

Monitore seus recursos de onde você estiver

Instale o app do Google Cloud Console para ajudar você a gerenciar seus projetos.

Enviar comentários sobre…

Cloud Storage Documentation