Hosting a static website

This tutorial describes how to configure a Cloud Storage bucket to host a static website for a domain you own. Static web pages can contain client-side technologies such as HTML, CSS, and JavaScript. They cannot contain dynamic content such as server-side scripts like PHP.

Since Cloud Storage doesn't support custom domains with HTTPS on its own, this tutorial uses Cloud Storage with HTTP(S) Load Balancing to serve content from a custom domain over HTTPS. For more ways to serve content from a custom domain over HTTPS, see the related troubleshooting topic. You can also use Cloud Storage to serve custom domain content over HTTP, which doesn't require a load balancer.

For examples and tips on static web pages, including how to host static assets for a dynamic website, see the Static Website page.

Objectives

This tutorial shows you how to:

  • Create a bucket.
  • Upload and share your site's files.
  • Set up a load balancer and SSL certificate.
  • Connect your load balancer to your bucket.
  • Point your domain to your load balancer using an A record.
  • Test the website.

Costs

This tutorial uses the following billable components of Google Cloud:

  • Cloud Storage
  • Cloud Load Balancing

See the Monitoring your 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. Sign in to your Google Account.

    If you don't already have one, sign up for a new account.

  2. In the Google Cloud Console, on the project selector page, select or create a Google Cloud project.

    Go to the project selector page

  3. Make sure that billing is enabled for your Cloud project. Learn how to confirm that billing is enabled for your project.

  4. Have a domain that you own or manage. If you don't have an existing domain, there are many services through which 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 that you will be using. Make sure you are verifying the top-level domain, such as example.com, and not a subdomain, 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.

  6. Have a few website files you want to serve. This tutorial works best if you have at least an index page (index.html) and a 404 page (404.html).
  7. Make sure you have either a project owner or editor role, or the following Identity and Access Management roles: Storage Object Admin and Network Admin.

Creating a bucket

To create a bucket named www.example.com:

Console

  1. Open the Cloud Storage browser in the Google Cloud Console.
    Open the Cloud Storage browser
  2. Click Create bucket to open the bucket creation form.

  3. Enter your bucket information and click Continue to complete each step:

    • Set the Name of your bucket, which we recommend making the same as your domain name to make a later step easier. For example, www.example.com.

    • Select the Location type and Location of your bucket. For example, Region and us-east1.

    • Select Standard Storage for the Storage class.

    • Select Uniform for Access control.

  4. Click Create.

If successful, the Bucket details page opens and displays the text "There are no live objects in this bucket."

See Troubleshooting for how to get detailed error information about failed operations in the Cloud Storage browser.

gsutil

Use the gsutil mb command:

gsutil mb -b on gs://www.example.com

If successful, the command returns:

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

Code samples

C++

For more information, see the Cloud Storage C++ API reference documentation.

namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
  StatusOr<gcs::BucketMetadata> bucket_metadata =
      client.CreateBucket(bucket_name, gcs::BucketMetadata());

  if (!bucket_metadata) {
    throw std::runtime_error(bucket_metadata.status().message());
  }

  std::cout << "Bucket " << bucket_metadata->name() << " created."
            << "\nFull Metadata: " << *bucket_metadata << "\n";
}

C#

For more information, see the Cloud Storage C# API reference documentation.


using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;

public class CreateBucketSample
{
    public Bucket CreateBucket(
        string projectId = "your-project-id",
        string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var bucket = storage.CreateBucket(projectId, bucketName);
        Console.WriteLine($"Created {bucketName}.");
        return bucket;
    }
}

Go

For more information, see the Cloud Storage Go API reference documentation.

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
)

// createBucketClassLocation creates a new bucket in the project with Storage class and
// location.
func createBucketClassLocation(w io.Writer, projectID, bucketName string) error {
	// projectID := "my-project-id"
	// bucketName := "bucket-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %v", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	storageClassAndLocation := &storage.BucketAttrs{
		StorageClass: "COLDLINE",
		Location:     "asia",
	}
	bucket := client.Bucket(bucketName)
	if err := bucket.Create(ctx, projectID, storageClassAndLocation); err != nil {
		return fmt.Errorf("Bucket(%q).Create: %v", bucketName, err)
	}
	fmt.Fprintf(w, "Created bucket %v in %v with storage class %v\n", bucketName, storageClassAndLocation.Location, storageClassAndLocation.StorageClass)
	return nil
}

Java

For more information, see the Cloud Storage Java API reference documentation.

import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageClass;
import com.google.cloud.storage.StorageOptions;

public class CreateBucketWithStorageClassAndLocation {
  public static void createBucketWithStorageClassAndLocation(String projectId, String bucketName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID to give your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();

    // See the StorageClass documentation for other valid storage classes:
    // https://googleapis.dev/java/google-cloud-clients/latest/com/google/cloud/storage/StorageClass.html
    StorageClass storageClass = StorageClass.COLDLINE;

    // See this documentation for other valid locations:
    // http://g.co/cloud/storage/docs/bucket-locations#location-mr
    String location = "ASIA";

    Bucket bucket =
        storage.create(
            BucketInfo.newBuilder(bucketName)
                .setStorageClass(storageClass)
                .setLocation(location)
                .build());

    System.out.println(
        "Created bucket "
            + bucket.getName()
            + " in "
            + bucket.getLocation()
            + " with storage class "
            + bucket.getStorageClass());
  }
}

Node.js

For more information, see the Cloud Storage Node.js API reference documentation.

/**
 * TODO(developer): Uncomment the following line before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';

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

// Creates a client
const storage = new Storage();

async function createBucket() {
  // Creates a new bucket in the Asia region with the coldline default storage
  // class. Leave the second argument blank for default settings.
  //
  // For default values see: https://cloud.google.com/storage/docs/locations and
  // https://cloud.google.com/storage/docs/storage-classes

  const [bucket] = await storage.createBucket(bucketName, {
    location: 'ASIA',
    storageClass: 'COLDLINE',
  });

  console.log(`Bucket ${bucket.name} created.`);
}

createBucket().catch(console.error);

PHP

For more information, see the Cloud Storage PHP API reference documentation.

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.
 *
 */
function create_bucket($bucketName, $options = [])
{
    $storage = new StorageClient();
    $bucket = $storage->createBucket($bucketName, $options);
    printf('Bucket created: %s' . PHP_EOL, $bucket->name());
}

Python

For more information, see the Cloud Storage Python API reference documentation.

from google.cloud import storage


def create_bucket_class_location(bucket_name):
    """Create a new bucket in specific location with storage class"""
    # bucket_name = "your-new-bucket-name"

    storage_client = storage.Client()

    bucket = storage_client.bucket(bucket_name)
    bucket.storage_class = "COLDLINE"
    new_bucket = storage_client.create_bucket(bucket, location="us")

    print(
        "Created bucket {} in {} with storage class {}".format(
            new_bucket.name, new_bucket.location, new_bucket.storage_class
        )
    )
    return new_bucket

Ruby

For more information, see the Cloud Storage Ruby API reference documentation.

# bucket_name   = "Name of Google Cloud Storage bucket to create"
# location      = "Location of where to create Cloud Storage bucket"
# storage_class = "Storage class of Cloud Storage bucket"

require "google/cloud/storage"

storage = Google::Cloud::Storage.new
bucket  = storage.create_bucket bucket_name,
                                location:      location,
                                storage_class: storage_class

puts "Created bucket #{bucket.name} in #{location}" \
     " with #{storage_class} class"

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 your website name to the name property:

    {
      "name": "www.example.com"
    }
  3. 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://storage.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

Add the files you want your website to serve to the bucket:

Console

  1. Open the Cloud Storage browser in the Google Cloud Console.
    Open the Cloud Storage browser
  2. In the list of buckets, click on the name of the bucket that you created.

    The Bucket details page opens, with the Objects tab selected.

  3. Click the Upload files button.

  4. In the file dialog, browse to the desired file and select it.

After the upload completes, you should see the file name along with file information displayed in the bucket.

See Troubleshooting for how to get detailed error information about failed operations in the Cloud Storage browser.

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

Code samples

C++

For more information, see the Cloud Storage C++ API reference documentation.

namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& file_name,
   std::string const& bucket_name, std::string const& object_name) {
  // Note that the client library automatically computes a hash on the
  // client-side to verify data integrity during transmission.
  StatusOr<gcs::ObjectMetadata> metadata = client.UploadFile(
      file_name, bucket_name, object_name, gcs::IfGenerationMatch(0));
  if (!metadata) throw std::runtime_error(metadata.status().message());

  std::cout << "Uploaded " << file_name << " to object " << metadata->name()
            << " in bucket " << metadata->bucket()
            << "\nFull metadata: " << *metadata << "\n";
}

C#

For more information, see the Cloud Storage C# API reference documentation.

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 information, see the Cloud Storage Go API reference documentation.

import (
	"context"
	"fmt"
	"io"
	"os"
	"time"

	"cloud.google.com/go/storage"
)

// uploadFile uploads an object.
func uploadFile(w io.Writer, bucket, object string) error {
	// bucket := "bucket-name"
	// object := "object-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %v", err)
	}
	defer client.Close()

	// Open local file.
	f, err := os.Open("notes.txt")
	if err != nil {
		return fmt.Errorf("os.Open: %v", err)
	}
	defer f.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*50)
	defer cancel()

	// Upload an object with storage.Writer.
	wc := client.Bucket(bucket).Object(object).NewWriter(ctx)
	if _, err = io.Copy(wc, f); err != nil {
		return fmt.Errorf("io.Copy: %v", err)
	}
	if err := wc.Close(); err != nil {
		return fmt.Errorf("Writer.Close: %v", err)
	}
	fmt.Fprintf(w, "Blob %v uploaded.\n", object)
	return nil
}

Java

For more information, see the Cloud Storage Java API reference documentation.

import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.BlobInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class UploadObject {
  public static void uploadObject(
      String projectId, String bucketName, String objectName, String filePath) throws IOException {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    // The ID of your GCS object
    // String objectName = "your-object-name";

    // The path to your file to upload
    // String filePath = "path/to/your/file"

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    BlobId blobId = BlobId.of(bucketName, objectName);
    BlobInfo blobInfo = BlobInfo.newBuilder(blobId).build();
    storage.create(blobInfo, Files.readAllBytes(Paths.get(filePath)));

    System.out.println(
        "File " + filePath + " uploaded to bucket " + bucketName + " as " + objectName);
  }
}

Node.js

For more information, see the Cloud Storage Node.js API reference documentation.

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const filename = 'Local file to upload, e.g. ./local/path/to/file.txt';

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

// Creates a client
const storage = new Storage();

async function uploadFile() {
  // Uploads a local file to the bucket
  await storage.bucket(bucketName).upload(filename, {
    // Support for HTTP requests made with `Accept-Encoding: gzip`
    gzip: true,
    // By setting the option `destination`, you can change the name of the
    // object you are uploading to a bucket.
    metadata: {
      // Enable long-lived HTTP caching headers
      // Use only if the contents of the file will never change
      // (If the contents will change, use cacheControl: 'no-cache')
      cacheControl: 'public, max-age=31536000',
    },
  });

  console.log(`${filename} uploaded to ${bucketName}.`);
}

uploadFile().catch(console.error);

PHP

For more information, see the Cloud Storage PHP API reference documentation.

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 information, see the Cloud Storage Python API reference documentation.

Use the Blob.upload_from_file(), Blob.upload_from_filename(), or Blob.upload_from_string() method to upload an object.
from google.cloud import storage


def upload_blob(bucket_name, source_file_name, destination_blob_name):
    """Uploads a file to the bucket."""
    # bucket_name = "your-bucket-name"
    # source_file_name = "local/path/to/file"
    # destination_blob_name = "storage-object-name"

    storage_client = storage.Client()
    bucket = storage_client.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 information, see the Cloud Storage Ruby API reference documentation.

# 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
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. 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://storage.googleapis.com/upload/storage/v1/b/www.example.com/o?uploadType=media&name=index.html"

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 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 make all objects in your bucket readable to everyone on the public internet:

Console

  1. Open the Cloud Storage browser in the Google Cloud Console.
    Open the Cloud Storage browser
  2. In the list of buckets, click on the name of the bucket that you want to make public.

  3. Select the Permissions tab near the top of the page.

  4. Click the Add members button.

    The Add members dialog box appears.

  5. In the New members field, enter allUsers.

  6. In the Select a role drop down, select the Cloud Storage sub-menu, and click the Storage Object Viewer option.

  7. Click Save.

  8. Click Allow public access.

Once shared publicly, a link icon appears for each object in the public access column. You can click on this icon to get the URL for the object.

See Troubleshooting for how to get detailed error information about failed operations in the Cloud Storage browser.

gsutil

Use the gsutil iam ch command:

gsutil iam ch allUsers:objectViewer gs://www.example.com

Code samples

C++

For more information, see the Cloud Storage C++ API reference documentation.

namespace gcs = google::cloud::storage;
using google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
  StatusOr<google::cloud::IamPolicy> current_policy =
      client.GetBucketIamPolicy(bucket_name);

  if (!current_policy) {
    throw std::runtime_error(current_policy.status().message());
  }

  current_policy->bindings.AddMember("roles/storage.objectViewer",
                                     "allUsers");

  // Update the policy. Note the use of `gcs::IfMatchEtag` to implement
  // optimistic concurrency control.
  StatusOr<google::cloud::IamPolicy> updated_policy =
      client.SetBucketIamPolicy(bucket_name, *current_policy,
                                gcs::IfMatchEtag(current_policy->etag));

  if (!updated_policy) {
    throw std::runtime_error(current_policy.status().message());
  }

  auto role = updated_policy->bindings.find("roles/storage.objectViewer");
  if (role == updated_policy->bindings.end()) {
    std::cout << "Cannot find 'roles/storage.objectViewer' in the updated"
              << " policy. This can happen if another application updates"
              << " the IAM policy at the same time. Please retry the"
              << " operation.\n";
    return;
  }
  auto member = role->second.find("allUsers");
  if (member == role->second.end()) {
    std::cout << "'allUsers' is not a member of the"
              << " 'roles/storage.objectViewer' role in the updated"
              << " policy. This can happen if another application updates"
              << " the IAM policy at the same time. Please retry the"
              << " operation.\n";
    return;
  }
  std::cout << "IamPolicy successfully updated for bucket " << bucket_name
            << '\n';
}

C#

For more information, see the Cloud Storage C# API reference documentation.


using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;
using System.Collections.Generic;

public class MakePublicSample
{
    public string MakePublic(
        string bucketName = "your-unique-bucket-name",
        string objectName = "your-object-name")
    {
        var storage = StorageClient.Create();
        var storageObject = storage.GetObject(bucketName, objectName);
        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);

        return storageObject.MediaLink;
    }
}

Java

For more information, see the Cloud Storage Java API reference documentation.

import com.google.cloud.Identity;
import com.google.cloud.Policy;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import com.google.cloud.storage.StorageRoles;

public class MakeBucketPublic {
  public static void makeBucketPublic(String projectId, String bucketName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Policy originalPolicy = storage.getIamPolicy(bucketName);
    storage.setIamPolicy(
        bucketName,
        originalPolicy
            .toBuilder()
            .addIdentity(StorageRoles.objectViewer(), Identity.allUsers()) // All users can view
            .build());

    System.out.println("Bucket " + bucketName + " is now publicly readable");
  }
}

Python

For more information, see the Cloud Storage Python API reference documentation.

from google.cloud import storage


def set_bucket_public_iam(bucket_name, role, member):
    """Set a public IAM Policy to bucket"""
    # bucket_name = "your-bucket-name"
    # role = "IAM role, e.g. roles/storage.objectViewer"
    # member = "IAM identity, e.g. allUsers"

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)

    policy = bucket.get_iam_policy(requested_policy_version=3)
    policy.bindings.append({"role": role, "members": {member}})

    bucket.set_iam_policy(policy)

    print("Bucket {} is now publicly readable".format(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 contains the following information:

    {
      "bindings":[
        {
          "role": "roles/storage.objectViewer",
          "members":["allUsers"]
        }
      ]
    }
  3. Use cURL to call the JSON API with a PUT Bucket request:

    curl -X PUT --data-binary @JSON_FILE_NAME.json \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      -H "Content-Type: application/json" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/iam"

    Where:

    • JSON_FILE_NAME is the name of the file you created in Step 2.
    • OAUTH2_TOKEN is the access token you created in Step 1.
    • BUCKET_NAME is the name of the bucket whose objects you want to make public. For example, my-bucket.

XML API

Making all objects in a bucket publicly readable is not supported by the XML API. Use gsutil or the JSON API instead, or set ACLs for each individual object.

To make individual objects in your bucket publicly accessible, you need to switch your bucket's Access control mode to Fine-grained. Generally, making all files in your bucket publicly accessible is easier and faster.

Visitors receive a http 403 response code when requesting the URL for a non-public or non-existent file. See the next section for information on how to add an error page that uses a http 404 response code.

Recommended: Assigning specialty pages

You can assign an index page suffix, which is controlled by the MainPageSuffix property, and a custom error page, which is controlled by the NotFoundPage property. Assigning either is optional, but without an index page, nothing is served when users access your top-level site, for example, https://www.example.com. For more information about the MainPageSuffix and NotFoundPage properties, see Specialty pages.

In the following sample, the MainPageSuffix is set to index.html and NotFoundPage is set to 404.html:

Console

  1. Open the Cloud Storage browser in the Google Cloud Console.
    Open the Cloud Storage browser
  2. In the list of buckets, find the bucket you created.

  3. Click the Bucket overflow menu () associated with the bucket and select Edit website configuration.

  4. In the website configuration dialog, specify the main page and error page.

  5. Click Save.

See Troubleshooting for how to get detailed error information about failed operations in the Cloud Storage browser.

gsutil

Use the gsutil web set command to set the MainPageSuffix property with the -m flag and the NotFoundPage with the -e flag:

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/...

Code samples

C++

For more information, see the Cloud Storage C++ API reference documentation.

namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& main_page_suffix, std::string const& not_found_page) {
  StatusOr<gcs::BucketMetadata> original =
      client.GetBucketMetadata(bucket_name);

  if (!original) throw std::runtime_error(original.status().message());
  StatusOr<gcs::BucketMetadata> patched_metadata = client.PatchBucket(
      bucket_name,
      gcs::BucketMetadataPatchBuilder().SetWebsite(
          gcs::BucketWebsite{main_page_suffix, not_found_page}),
      gcs::IfMetagenerationMatch(original->metageneration()));

  if (!patched_metadata) {
    throw std::runtime_error(patched_metadata.status().message());
  }

  if (!patched_metadata->has_website()) {
    std::cout << "Static website configuration is not set for bucket "
              << patched_metadata->name() << "\n";
    return;
  }

  std::cout << "Static website configuration successfully set for bucket "
            << patched_metadata->name() << "\nNew main page suffix is: "
            << patched_metadata->website().main_page_suffix
            << "\nNew not found page is: "
            << patched_metadata->website().not_found_page << "\n";
}

Java

For more information, see the Cloud Storage Java API reference documentation.

import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class SetBucketWebsiteInfo {
  public static void setBucketWesbiteInfo(
      String projectId, String bucketName, String indexPage, String notFoundPage) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your static website bucket
    // String bucketName = "www.example.com";

    // The index page for a static website bucket
    // String indexPage = "index.html";

    // The 404 page for a static website bucket
    // String notFoundPage = "404.html";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Bucket bucket = storage.get(bucketName);
    bucket.toBuilder().setIndexPage(indexPage).setNotFoundPage(notFoundPage).build().update();

    System.out.println(
        "Static website bucket "
            + bucketName
            + " is set up to use "
            + indexPage
            + " as the index page and "
            + notFoundPage
            + " as the 404 page");
  }
}

Python

For more information, see the Cloud Storage Python API reference documentation.

from google.cloud import storage


def define_bucket_website_configuration(bucket_name, main_page_suffix, not_found_page):
    """Configure website-related properties of bucket"""
    # bucket_name = "your-bucket-name"
    # main_page_suffix = "index.html"
    # not_found_page = "404.html"

    storage_client = storage.Client()

    bucket = storage_client.get_bucket(bucket_name)
    bucket.configure_website(main_page_suffix, not_found_page)
    bucket.patch()

    print(
        "Static website bucket {} is set up to use {} as the index page and {} as the 404 page".format(
            bucket.name, main_page_suffix, not_found_page
        )
    )
    return bucket

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://storage.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

Setting up your load balancer and SSL certificate

Cloud Storage doesn't support custom domains with HTTPS on its own, so you also need to set up an SSL certificate attached to an HTTPS load balancer to serve your website through HTTPS. This section shows you how to add your bucket to a load balancer's backend and how to add a new Google-managed SSL certificate to the load balancer's front end.

  1. Go to the Load balancing page in the Google Cloud Console.
    Go to the Load balancing page
  2. Under HTTP(S) load balancing, click Start configuration.
  3. Select From Internet to my VMs and click Continue.
  4. Give your load balancer a Name, such as example-lb.

Configuring the backend

  1. Click Backend configuration.
  2. In the Create or select backend services & backend buckets dropdown, go to the Backend buckets sub-menu, and click the Create a backend bucket option.
  3. Choose a Name for the backend bucket, such as example-bucket.
  4. Click Browse under Cloud Storage bucket.
  5. Select the www.example.com bucket and click Select.
  6. Click Create.

Configuring host rules and path matchers

Host rules and path matchers are configuration components of an external HTTP(S) load balancer's URL map.

  1. Click Host and path rules.
  2. Leave Mode at the default Simple host and path rule for the backend bucket example-bucket, which you created earlier.

Configuring the frontend

This section shows you how to configure the HTTPS protocol and create an SSL certificate. You can also select an existing certificate or upload a self-managed SSL certificate.

  1. Click Frontend configuration.
  2. Configure the values for the following fields:

  3. For the IP address field:

    1. In the dropdown, click Create IP address.
    2. In the Reserve a new static IP address pop-up, enter example-ip for the Name of the IP address.
    3. Click Reserve
  4. For Port, select 443.

  5. For the Certificate field, select Create a new certificate. The certificate creation form appears in a panel. Configure the following:

    • Name: example-ssl
    • Create mode: Create Google-managed certificate
    • Domains: www.example.com. If you want to serve your content through additional domains such as the root domain example.com, press Enter to add them on additional lines. Each certificate has a limit of 100 domains.
  6. Click Create.

  7. Click Done.

Reviewing the configuration

  1. Click Review and finalize.
  2. Review the Backend configuration, Host and path rules, and Frontend configuration.
  3. Click Create.

You may need to wait a few minutes for the load balancer to be created.

Connecting your domain to your load balancer

After the load balancer is created, click the name of your load balancer: example-lb. Note the IP address associated with the load balancer: for example, 30.90.80.100. To point your domain to your load balancer, create an A record using your domain registration service. If you added multiple domains to your SSL certificate, you must add an A record for each one, all pointing to the load balancer's IP address. For example, to create A records for www.example.com and example.com:

NAME                  TYPE     DATA
www                   A        30.90.80.100
@                     A        30.90.80.100

If you are using Google Domains, see Create an A or CNAME record for more information.

It might take up to 60-90 minutes for Google Cloud to provision the certificate and make the site available through the load balancer. To monitor the status of your certificate:

Console

  1. Go to the Load balancing page in the Google Cloud Console.
    Go to the Load balancing page
  2. Click on the name of your load balancer: example-lb.
  3. Click on the name of the SSL certificate associated with the load balancer: example-ssl.
  4. The Status and Domain status rows show the certificate status. Both must be active in order for the certificate to be valid for your website.

gcloud

  1. To check the certificate status, run the following command:

    gcloud beta compute ssl-certificates describe certificate-name \
      --global \
      --format="get(name,managed.status)"
    
  2. To check the domain status, run the following command:

    gcloud beta compute ssl-certificates describe certificate-name \
      --global \
      --format="get(managed.domainStatus)"
    

See Troubleshooting SSL certificates for more information about certificate status.

Testing the website

Once the SSL certificate is active, verify that content is served from the bucket by going to https://www.example.com/test.html, where test.html is an object stored in a bucket named www.example.com. If you set the MainPageSuffix property, https://www.example.com goes to index.html.

Cleaning up

After you've finished the Hosting a static website tutorial, you can clean up the resources that you created on Google Cloud so they won't take up quota and 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 that you created for the tutorial.

To delete the project:

  1. In the Cloud Console, go to the Manage resources page.

    Go to the Manage resources page

  2. In the project list, select the project that you want to delete and then click Delete .
  3. In the dialog, type the project ID and then click Shut down to delete the project.

Deleting the load balancer and bucket

If you don't want to delete the entire project, delete the load balancer and bucket that you created for the tutorial:

  1. Go to the Load balancing page in the Google Cloud Console.
    Go to the Load balancing page
  2. Select the checkbox next to example-lb.
  3. Click Delete.
  4. (Optional) Select the checkbox next to the resources you want to delete along with the load balancer, such as the www.example.com bucket or the example-ssl SSL certificate.
  5. Click Delete load balancer or Delete load balancer and the selected resources.

What's next

Try it for yourself

If you're new to Google Cloud, create an account to evaluate how Cloud Storage performs in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.

Try Cloud Storage free