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. For more information on static web pages, such as examples and tips, 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 by using a CNAME record.
  • 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:

  • Cloud Storage

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

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

  2. Select or create a GCP project.

    Go to the Manage resources page

  3. Make sure that billing is enabled for your project.

    Learn how to enable billing

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

Creating a CNAME record

A CNAME record is a type of DNS record. It directs traffic that requests a URL from your domain to the resources you want to serve, in this case objects in your Cloud Storage buckets. For www.example.com, the CNAME record might contain the following information:

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

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

To connect your domain to Cloud Storage:

  1. Create a CNAME record that points to c.storage.googleapis.com..

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

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.

  4. Click Create.

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

Code samples

C++

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

namespace gcs = google::cloud::storage;
[](gcs::Client client, std::string bucket_name) {
  gcs::BucketMetadata meta =
      client.CreateBucket(bucket_name, gcs::BucketMetadata());
  std::cout << "Bucket created.  The metadata is " << meta << std::endl;
}

C#

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

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

Go

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

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

Java

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

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

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

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

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

// Creates a new bucket
await storage.createBucket(bucketName, {
  location: 'ASIA',
  storageClass: 'COLDLINE',
});

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

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

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

# project_id    = "Your Google Cloud project ID"
# 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 project_id: project_id
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 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 name of the bucket that you created.

  3. Click the Upload files button in the Objects tab.

  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 GCP 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

Code samples

C++

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

namespace gcs = google::cloud::storage;
[](gcs::Client client, std::string bucket_name, std::string object_name,
   std::string contents) {
  gcs::ObjectMetadata meta =
      client.InsertObject(bucket_name, object_name, std::move(contents));
  std::cout << "The file was uploaded. The new object metadata is " << meta
            << std::endl;
}

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 .

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

Storage storage = StorageOptions.getDefaultInstance().getService();
BlobId blobId = BlobId.of("bucket", "blob_name");
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build();
Blob blob = storage.create(blobInfo, "Hello, Cloud Storage!".getBytes(UTF_8));

Node.js

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

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

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

/**
 * 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';

// Uploads a local file to the bucket
await storage.bucket(bucketName).upload(filename, {
  // Support for HTTP requests made with `Accept-Encoding: gzip`
  gzip: true,
  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}.`);

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

# 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_id: 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

You can either make all files in your bucket publicly accessible, or you can set individual objects to be accessible through your website. Generally, making all files in your bucket accessible is easier and faster.

If you choose to control the accessibility of individual files, you can set the default object ACL for your bucket so that subsequent files uploaded to your bucket are shared by default.

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, http://www.example.com.

Index pages

An index page (also called a webserver directory index) is a file served to visitors when they request a URL that doesn't have an associated file. When you assign a MainPageSuffix, Cloud Storage looks for a file with that name whose prefix matches the URL the visitor requested.

For example, say you set the MainPageSuffix of your static website to index.html. Additionally, say you have no file named directory in your bucket www.example.com. In this situation, if a user requests the URL http://www.example.com/directory, Cloud Storage attempts to serve the file www.example.com/directory/index.html. If that file also doesn't exist, Cloud Storage returns an error page.

The MainPageSuffix also controls the file served when users request the top level site. Continuing the above example, if a user requests http://www.example.com, Cloud Storage attempts to serve the file www.example.com/index.html.

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 a MainPageSuffix, Cloud Storage only returns the error page if there is neither a file with the requested name nor an applicable index page.

When returning an error page, the http response code is 404. 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.

Setting MainPageSuffix and NotFoundPage

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

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

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

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

For example, if you have an object named test.html stored in a bucket named www.example.com, check that it's accessible by going to www.example.com/test.html in your browser.

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 GCP 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 of the bucket you want to delete.

  3. Click Delete.

  4. In the overlay window that appears, confirm you want to delete the bucket and its contents by clicking Delete.

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

The response looks like the following example:

Removing gs://www.example.com/...

Code samples

C++

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

namespace gcs = google::cloud::storage;
[](gcs::Client client, std::string bucket_name) {
  client.DeleteBucket(bucket_name);
}

C#

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

private void DeleteBucket(string bucketName)
{
    var storage = StorageClient.Create();
    storage.DeleteBucket(bucketName);
    Console.WriteLine($"Deleted {bucketName}.");
}

Go

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

if err := client.Bucket(bucketName).Delete(ctx); err != nil {
	return err
}

Java

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

boolean deleted = bucket.delete(BucketSourceOption.metagenerationMatch());
if (deleted) {
  // the bucket was deleted
} else {
  // the bucket was not found
}

Node.js

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

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

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

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

// Deletes the bucket
await storage.bucket(bucketName).delete();

console.log(`Bucket ${bucketName} deleted.`);

PHP

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

use Google\Cloud\Storage\StorageClient;

/**
 * Delete a Cloud Storage Bucket.
 *
 * @param string $bucketName the name of the bucket to delete.
 *
 * @return void
 */
function delete_bucket($bucketName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $bucket->delete();
    printf('Bucket deleted: %s' . PHP_EOL, $bucket->name());
}

Python

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

def delete_bucket(bucket_name):
    """Deletes a bucket. The bucket must be empty."""
    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucket_name)
    bucket.delete()
    print('Bucket {} deleted'.format(bucket.name))

Ruby

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

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

require "google/cloud/storage"

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

bucket.delete

puts "Deleted bucket: #{bucket.name}"

REST APIs

JSON API

Note that your bucket must be empty before you can delete it.

  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, replacing [VALUES_IN_BRACKETS] with the appropriate values:
    curl -X DELETE -H "Authorization: Bearer [OAUTH2_TOKEN]" \
        "https://www.googleapis.com/storage/v1/b/www.example.com"

If successful, the response contains a 204 status code.

See the Buckets: delete JSON reference page for more information.

XML API

Note that your bucket must be empty before you can delete it.

  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, replacing [VALUES_IN_BRACKETS] with the appropriate values:
    curl -X DELETE -H "Authorization: Bearer [OAUTH2_TOKEN]" \
        "https://storage.googleapis.com/www.example.com"

See the Delete Bucket XML reference page for more information.

What's next

Var denne side nyttig? Giv os en anmeldelse af den:

Send feedback om...

Har du brug for hjælp? Besøg vores supportside.