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

This tutorial shows you how to serve content over HTTP. For a tutorial that uses HTTPS, see Hosting a static website

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

## ObjectivesIn this tutorial you will:
- Point your domain to Cloud Storage by using a
CNAMErecord

- 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 Google Cloud:
- 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
- Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads

-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project

-
Make sure that billing is enabled for your Cloud project. Learn how to check if billing is enabled on a project

-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project

-
Make sure that billing is enabled for your Cloud project. Learn how to check if billing is enabled on a project

- 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

- 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

## Connecting your domain to Cloud Storage
To connect your domain to Cloud Storage, create a
CNAME record
through your domain registration service. 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 CNAME c.storage.googleapis.com

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

To connect your domain to Cloud Storage:
Create a
CNAMErecord that points to
c.storage.googleapis.com.

Your domain registration service should have a way for you to administer your domain, including adding a
CNAMErecord. For example, if you use Google Domains, instructions for adding resource records can be found on the Google Domains Help page

## 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 from the
www subdomain of
example.com to
c.storage.googleapis.com., then create a bucket with
the name "www.example.com"

To create a bucket:
 Console
- In the Google Cloud console, go to the Cloud Storage
Bucketspage

Click
Create bucketto open the bucket creation form

Enter your bucket information and click
Continueto complete each step:
The
Nameof your bucket, which matches the hostname associated with your
CNAMErecord

Select the
Location typeand Location of your bucket. For example, Regionand us-east1

Select
Standard Storagefor the Storage class

Select
Uniformfor Access control

-
Click
Create

If successful, you are taken to the bucket's page with the text "There are no live objects in this bucket."
 gsutil
Use the
gsutil mb command:
gsutil mb gswww.example.com
If successful, the command returns:
Creating gswww.example.com

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

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

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

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

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

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

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

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

## C++
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
gcs::Client client, std::string const& bucket_name,
std::string const& storage_class, std::string const& location) {
StatusOr bucket_metadata =
client.CreateBucket(bucket_name, gcs::BucketMetadata()
.set_storage_class(storage_class)
.set_location(location
if (!bucket_metadata) {
throw std::runtime_error(bucket_metadata.statusmessage
}
std::cout << "Bucket " << bucket_metadata->name() << " created."
<< "\nFull Metadata: " << *bucket_metadata << "\n";
}
## C#
using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;
public class CreateRegionalBucketSample
{
 
 Creates a storage bucket with region

 
 The ID of the project to create the buckets inparam>
 The location of the bucket. Object data for objects in the bucket resides in
 physical storage within this region. Defaults to USparam>
 The name of the bucket to createparam>
 The bucket's default storage class, used whenever no storageClass is specified
 for a newly-created object. This defines how objects in the bucket are stored
 and determines the SLA and the cost of storage. Values include MULTI_REGIONAL,
 REGIONAL, STANDARD, NEARLINE, COLDLINE, ARCHIVE, and DURABLE_REDUCED_AVAILABILITY

 If this value is not specified when the bucket is created, it will default to
 STANDARDparam>
public Bucket CreateRegionalBucket(
string projectId = "your-project-id",
string bucketName = "your-unique-bucket-name",
string location = "us-west1",
string storageClass = "REGIONAL")
{
var storage = StorageClient.Create
Bucket bucket = new Bucket
{
Location = location,
Name = bucketName,
StorageClass = storageClass
};
var newlyCreatedBucket = storage.CreateBucket(projectId, bucket);
Console.WriteLineCreated {bucketName
return newlyCreatedBucket;
}
}
## Go
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*30)
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
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.newBuildersetProjectId(projectId).buildgetService
// See the StorageClass documentation for other valid storage classes:
// httpsgoogleapis.dev/java/google-cloud-clients/latest/com/google/cloud/storage/StorageClass.html
StorageClass storageClass = StorageClass.COLDLINE;
// See this documentation for other valid locations:
// httpg.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

* TODO(developer): Uncomment the following lines before running the sample

*/
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';
// The name of a storage class
// See the StorageClass documentation for other valid storage classes:
// httpsgoogleapis.dev/java/google-cloud-clients/latest/com/google/cloud/storage/StorageClass.html
// const storageClass = 'coldline';
// The name of a location
// See this documentation for other valid locations:
// httpg.co/cloud/storage/docs/locations#location-mr
// const location = 'ASIA';
// Imports the Google Cloud client library
const {Storage} = requiregoogle-cloud/storage
// Creates a client
// The bucket in the sample below will be created in the project associated with this client

// For more information, please see httpscloud.google.com/docs/authentication/production or httpsgoogleapis.dev/nodejs/storage/latest/Storage.html
const storage = new Storage
async function createBucketWithStorageClassAndLocation() {
// For default values see: httpscloud.google.com/storage/docs/locations and
// httpscloud.google.com/storage/docs/storage-classes
const [bucket] = await storage.createBucket(bucketName, {
location,
[storageClass]: true,

console.log(
bucket.name} created with ${storageClass} class in ${location}`
);
}
createBucketWithStorageClassAndLocationcatch(console.error);
## PHP
use Google\Cloud\Storage\StorageClient;

* Create a new bucket with a custom default storage class and location

*
* @param string $bucketName The name of your Cloud Storage bucket

* (e.g. 'my-bucket')
*/
function create_bucket_class_location(string $bucketName): void
{
$storage = new StorageClient
$storageClass = 'COLDLINE';
$location = 'ASIA';
$bucket = $storage->createBucket($bucketName, [
'storageClass' => $storageClass,
'location' => $location,

$objects = $bucket->objects([
'encryption' => [
'defaultKmsKeyName' => null,
]

printf('Created bucket %s in %s with storage class %s', $bucketName, $storageClass, $location);
}
## Python
from google.cloud import storage
def create_bucket_class_location(bucket_name):

Create a new bucket in the US region with the coldline 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
def create_bucket_class_location bucket_name:
# The ID to give your GCS bucket
# bucket_name = "your-unique-bucket-name"
require "google/cloud/storage"
storage = Google::Cloud::Storage.new
bucket = storage.create_bucket bucket_name,
location: "ASIA",
storage_class: "COLDLINE"
puts "Created bucket #{bucket.name} in #{bucket.location} with #{bucket.storage_class} class"
end
For more information, see the Cloud Storage C++ API reference documentation

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

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

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

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

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

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

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

 REST APIs
 JSON API
- Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials. For instructions, see API authentication

Create a JSON file that assigns your website name to the
nameproperty:
{ "name": "www.example.com" }
Use
cURLto 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" \ "httpsstorage.googleapis.com/storage/v1/b?project=my-static-website"
 XML API
- Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials. For instructions, see API authentication

Use
cURLto 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" \ "httpsstorage.googleapis.com/www.example.com"
## Uploading your site's files
To add to your bucket the files you want your website to serve:
 Console
- In the Google Cloud console, go to the Cloud Storage
Bucketspage

In the list of buckets, click on the name of the bucket that you created

Click the
Upload filesbutton in the Objectstab

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

 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 gswww.example.com
If successful, the command returns:
Copying fileDesktop/index.html [Content-Type=text/html Uploading gswww.example.com/index.html: 0 B/2.58 KiB Uploading gswww.example.com/index.html: 2.58 KiB/2.58 KiB
 Code samples
For more information, see the
Cloud Storage C++ API
reference documentation

The following sample uploads an object from a file: The following sample uploads an object from memory:
For more information, see the
Cloud Storage C# API
reference documentation

The following sample uploads an object from a file: The following sample uploads an object from memory:
For more information, see the
Cloud Storage Go API
reference documentation

The following sample uploads an object from a file: The following sample uploads an object from memory:
For more information, see the
Cloud Storage Java API
reference documentation

The following sample uploads an object from a file: The following sample uploads an object from memory:
For more information, see the
Cloud Storage Node.js API
reference documentation

The following sample uploads an object from a file: The following sample uploads an object from memory:
For more information, see the
Cloud Storage PHP API
reference documentation

The following sample uploads an object from a file: The following sample uploads an object from memory:
For more information, see the
Cloud Storage Python API
reference documentation

The following sample uploads an object from a file: The following sample uploads an object from memory:
For more information, see the
Cloud Storage Ruby API
reference documentation

The following sample uploads an object from a file: The following sample uploads an object from memory:
## C++
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

StatusOrrmetadata = client.UploadFile(
file_name, bucket_name, object_name, gcs::IfGenerationMatch(0
if (!metadata) throw std::runtime_error(metadata.statusmessage
std::cout <<<"Uploaded " <<<file_name <<<" to object " <<name()
<<<" in bucket " <<bucket()
<<<"\nFull metadata: " <<<*metadata <<<"\n";
}
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
gcs::Client client, std::string const&tbucket_name,
std::string const&tobject_name) {
std::string const text = "Lorem ipsum dolor sit amet";
std::vectororv(100, text);
gcs::ObjectWriteStream stream =
client.WriteObject(bucket_name, object_name);
std::copy(v.begin v.end std::ostream_iteratorrstream.Close
StatusOrOrmetadata = std::move(stream).metadata
if (!metadata) throw std::runtime_error(metadata.statusmessage
std::cout <<<"Successfully wrote to object " <<name()
<<<" its size is: " <<size()
<<<"\nFull metadata: " <<<*metadata <<"\n";
}
## C#
using Google.Cloud.Storage.V1;
using System;
using System.IO;
public class UploadFileSample
{
public void UploadFile(
string bucketName = "your-unique-bucket-name",
string localPath = "my-local-path/my-file-name",
string objectName = "my-file-name")
{
var storage = StorageClient.Create
using var fileStream = File.OpenRead(localPath);
storage.UploadObject(bucketName, objectName, null, fileStream);
Console.WriteLineUploaded {objectName
}
}
using Google.Cloud.Storage.V1;
using System;
using System.IO;
using System.Text;
public class UploadObjectFromMemorySample
{
public void UploadObjectFromMemory(
string bucketName = "unique-bucket-name",
string objectName = "file-name",
string contents = "Hello world
{
var storage = StorageClient.Create
byte[] byteArray = Encoding.UTF8.GetBytes(contents);
MemoryStream stream = new MemoryStream(byteArray);
storage.UploadObject(bucketName, objectName, "application/octet-stream" , stream);
Console.WriteLine {objectName} uploaded to bucket {bucketName} with contents: {contents
}
}
## Go
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()
o := client.Bucket(bucket).Object(object)
// Optional: set a generation-match precondition to avoid potential race
// conditions and data corruptions. The request to upload is aborted if the
// object's generation number does not match your precondition

// For an object that does not yet exist, set the DoesNotExist precondition

o = o.If(storage.Conditions{DoesNotExist: true})
// If the live object already exists in your bucket, set instead a
// generation-match precondition using the live object's generation number

// attrs, err := o.Attrs(ctx)
// if err != nil {
// return fmt.Errorf("object.Attrs: %v", err)
// }
// o = o.If(storage.Conditions{GenerationMatch: attrs.Generation})
// Upload an object with storage.Writer

wc := o.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
}
import (
"bytes"
"context"
"fmt"
"io"
"time"
"cloud.google.com/go/storage"
)
// streamFileUpload uploads an object via a stream

func streamFileUpload(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()
b := []byte("Hello world
buf := bytes.NewBuffer(b)
ctx, cancel := context.WithTimeout(ctx, time.Second*50)
defer cancel()
// Upload an object with storage.Writer

wc := client.Bucket(bucket).Object(object).NewWriter(ctx)
wc.ChunkSize = 0 // note retries are not supported for chunk size 0

if _, err = io.Copy(wc, buf); err != nil {
return fmt.Errorf("io.Copy: %v", err)
}
// Data can continue to be added to the file until the writer is closed

if err := wc.Close err != nil {
return fmt.Errorf("Writer.Close: %v", err)
}
fmt.Fprintf(w, "%v uploaded to %v.\n", object, bucket)
return nil
}
## Java
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"
// Optional: set a generation-match precondition to avoid potential race
// conditions and data corruptions. The request returns a 412 error if the
// preconditions are not met

// For a target object that does not yet exist, set the DoesNotExist precondition

Storage.BlobTargetOption precondition = Storage.BlobTargetOption.doesNotExist
// If the destination already exists in your bucket, instead set a generation-match
// precondition:
// Storage.BlobTargetOption precondition = Storage.BlobTargetOption.generationMatch
Storage storage = StorageOptions.newBuildersetProjectId(projectId).buildgetService
BlobId blobId = BlobId.of(bucketName, objectName);
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).build
storage.create(blobInfo, Files.readAllBytes(Paths.get(filePath precondition);
System.out.println(
"File " + filePath + " uploaded to bucket " + bucketName + " as " + objectName);
}
}
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.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class UploadObjectFromMemory {
public static void uploadObjectFromMemory(
String projectId, String bucketName, String objectName, String contents) 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 string of contents you wish to upload
// String contents = "Hello world
Storage storage = StorageOptions.newBuildersetProjectId(projectId).buildgetService
BlobId blobId = BlobId.of(bucketName, objectName);
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).build
byte[] content = contents.getBytes(StandardCharsets.UTF_8);
storage.createFrom(blobInfo, new ByteArrayInputStream(content
System.out.println(
"Object "
+ objectName
+ " uploaded to bucket "
+ bucketName
+ " with contents "
+ contents);
}
}
## Node.js

* TODO(developer): Uncomment the following lines before running the sample

*/
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';
// The path to your file to upload
// const filePath = 'path/to/your/file';
// The new ID for your GCS file
// const destFileName = 'your-new-file-name';
// Imports the Google Cloud client library
const {Storage} = requiregoogle-cloud/storage
// Creates a client
const storage = new Storage
async function uploadFile() {
const options = {
destination: destFileName,
// Optional:
// Set a generation-match precondition to avoid potential race conditions
// and data corruptions. The request to upload is aborted if the object's
// generation number does not match your precondition. For a destination
// object that does not yet exist, set the ifGenerationMatch precondition to 0
// If the destination object already exists in your bucket, set instead a
// generation-match precondition using its generation number

preconditionOpts: {ifGenerationMatch: generationMatchPrecondition},
};
await storage.bucket(bucketName).upload(filePath, options);
console.logfilePath} uploaded to ${bucketName
}
uploadFilecatch(console.error);

* TODO(developer): Uncomment the following lines before running the sample

*/
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';
// The contents that you want to upload
// const contents = 'these are my contents';
// The new ID for your GCS file
// const destFileName = 'your-new-file-name';
// Imports the Google Cloud Node.js client library
const {Storage} = requiregoogle-cloud/storage
// Creates a client
const storage = new Storage
async function uploadFromMemory() {
await storage.bucket(bucketName).file(destFileName).save(contents);
console.log(
destFileName} with contents ${contents} uploaded to ${bucketName
);
}
uploadFromMemorycatch(console.error);
## PHP
use Google\Cloud\Storage\StorageClient;

* Upload a file

*
* @param string $bucketName The name of your Cloud Storage bucket

* (e.g. 'my-bucket')
* @param string $objectName The name of your Cloud Storage object

* (e.g. 'my-object')
* @param string $source The path to the file to upload

* (e.g. '/path/to/your/file')
*/
function upload_object(string $bucketName, string $objectName, string $source): void
{
$storage = new StorageClient
$file = fopen($source, 'r
$bucket = $storage->bucket($bucketName);
$object = $bucket->upload($file, [
'name' => $objectName

printf('Uploaded %s to gss/%s' . PHP_EOL, basename($source), $bucketName, $objectName);
}
use Google\Cloud\Storage\StorageClient;

* Upload an object from memory buffer

*
* @param string $bucketName The name of your Cloud Storage bucket

* (e.g. 'my-bucket')
* @param string $objectName The name of your Cloud Storage object

* (e.g. 'my-object')
* @param string $contents The contents to upload to the file

* (e.g. 'these are my contents')
*/
function upload_object_from_memory(
string $bucketName,
string $objectName,
string $contents
): void {
$storage = new StorageClient
$stream = fopen('datatext/plain,' . $contents, 'r
$bucket = $storage->bucket($bucketName);
$bucket->upload($stream, [
'name' => $objectName,

printf('Uploaded %s to gss/%s' . PHP_EOL, $contents, $bucketName, $objectName);
}
## Python
from google.cloud import storage
def upload_blob(bucket_name, source_file_name, destination_blob_name):
Uploads a file to the bucket
# The ID of your GCS bucket
# bucket_name = "your-bucket-name"
# The path to your file to upload
# source_file_name = "local/path/to/file"
# The ID of your GCS object
# 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(
f"File {source_file_name} uploaded to {destination_blob_name
)
from google.cloud import storage
def upload_blob_from_memory(bucket_name, contents, destination_blob_name):
Uploads a file to the bucket
# The ID of your GCS bucket
# bucket_name = "your-bucket-name"
# The contents to upload to the file
# contents = "these are my contents"
# The ID of your GCS object
# 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_string(contents)
print(
f"{destination_blob_name} with contents {contents} uploaded to {bucket_name
)
## Ruby
def upload_file bucket_name:, local_file_path:, file_name: nil
# The ID of your GCS bucket
# bucket_name = "your-unique-bucket-name"
# The path to your file to upload
# local_file_path = "/local/path/to/file.txt"
# The ID of your GCS object
# file_name = "your-file-name"
require "google/cloud/storage"
storage = Google::Cloud::Storage.new
bucket = storage.bucket bucket_name, skip_lookup: true
file = bucket.create_file local_file_path, file_name
puts "Uploaded #{local_file_path} as #{file.name} in bucket #{bucket_name}"
end
# The ID of your GCS bucket
# bucket_name = "your-unique-bucket-name"
# The ID of your GCS object
# file_name = "your-file-name"
# The contents to upload to your file
# file_content = "Hello, world!"
require "google/cloud/storage"
storage = Google::Cloud::Storage.new
bucket = storage.bucket bucket_name, skip_lookup: true
file = bucket.create_file StringIO.new(file_content), file_name
puts "Uploaded file #{file.name} to bucket #{bucket_name} with content: #{file_content}"
For more information, see the Cloud Storage C++ API reference documentation

The following sample uploads an object from a file:
The following sample uploads an object from memory:
For more information, see the Cloud Storage C# API reference documentation

The following sample uploads an object from a file:
The following sample uploads an object from memory:
For more information, see the Cloud Storage Go API reference documentation

The following sample uploads an object from a file:
The following sample uploads an object from memory:
For more information, see the Cloud Storage Java API reference documentation

The following sample uploads an object from a file:
The following sample uploads an object from memory:
For more information, see the Cloud Storage Node.js API reference documentation

The following sample uploads an object from a file:
The following sample uploads an object from memory:
For more information, see the Cloud Storage PHP API reference documentation

The following sample uploads an object from a file:
The following sample uploads an object from memory:
For more information, see the Cloud Storage Python API reference documentation

The following sample uploads an object from a file:
The following sample uploads an object from memory:
For more information, see the Cloud Storage Ruby API reference documentation

The following sample uploads an object from a file:
The following sample uploads an object from memory:
 REST APIs
 JSON API
- Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials. For instructions, see API authentication

Use
cURLto call the JSON API with a
POSTObject 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" \ "httpsstorage.googleapis.com/upload/storage/v1/b/www.example.com/o?uploadType=media&name=index.html"
 XML API
- Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials. For instructions, see API authentication

Use
cURLto call the XML API with a
PUTObject 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" \ "httpsstorage.googleapis.com/www.example.com/index.html"
## Sharing your files
To make all objects in a bucket readable to everyone on the public internet:
 Console
- In the Google Cloud console, go to the Cloud Storage
Bucketspage

In the list of buckets, click on the name of the bucket that you want to make public

Select the
Permissionstab near the top of the page

Click the
+ Addbutton

The
Add principalsdialog box appears

In the
New principalsfield, enter
allUsers

In the
Select a roledrop down, select the Cloud Storagesub-menu, and click the Storage Object Vieweroption

Click
Save

Click
Allow public access

Once shareda
**link** icon appears for each object in the *public
access* column. You can click on this icon to get the URL for the object

 gsutil
Use the
gsutil iam ch command:
gsutil iam ch allUsers:objectViewer gswww.example.com
 Code samples
For more information, see the
Cloud Storage C++ API
reference documentation

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

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

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

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

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

## C++
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
gcs::Client client, std::string const&nbucket_name) {
auto current_policy = client.GetNativeBucketIamPolicy(
bucket_name, gcs::RequestedPolicyVersion(3
if (!current_policy) {
throw std::runtime_error(current_policy.statusmessage
}
current_policy->set_version(3);
current_policy->bindingsemplace_back(
gcs::NativeIamBinding("roles/storage.objectViewer", {"allUsers
auto updated =
client.SetNativeBucketIamPolicy(bucket_name, *current_policy);
if (!updated) throw std::runtime_error(updated.statusmessage
std::cout <import (
"context"
"fmt"
"io"
"cloud.google.com/go/iam"
"cloud.google.com/go/storage"
iampb "google.golang.org/genproto/googleapis/iam/v1"
)
// setBucketPublicIAM makes all objects in a bucketreadable

func setBucketPublicIAM(w io.Writer, bucketName string) error {
// bucketName := "bucket-name"
ctx := context.Background()
client, err := storage.NewClient(ctx)
if err != nil {
return fmt.Errorf("storage.NewClient: %v", err)
}
defer client.Close()
policy, err := client.Bucket(bucketName).IAMV3Policy(ctx)
if err != nil {
return fmt.Errorf("Bucket(%q).IAMV3Policy: %v", bucketName, err)
}
role := "roles/storage.objectViewer"
policy.Bindings = append(policy.Bindings, &iampb.Binding{
Role: role,
Members: []string{iam.AllUsers},
})
if err := client.Bucket(bucketName).IAMV3SetPolicy(ctx, policy); err != nil {
return fmt.Errorf("Bucket(%q).IAMSetPolicy: %v", bucketName, err)
}
fmt.Fprintf(w, "Bucket %v is nowreadable\n", bucketName)
return nil
}
## Java
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.newBuildersetProjectId(projectId).buildgetService
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 nowreadable
}
}
## Node.js

* TODO(developer): Uncomment the following lines before running the sample

*/
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';
// Imports the Google Cloud client library
const {Storage} = requiregoogle-cloud/storage
// Creates a client
const storage = new Storage
async function makeBucketPublic() {
await storage.bucket(bucketName).makePublic
console.log(`Bucket ${bucketName} is nowreadable
}
makeBucketPubliccatch(console.error);
## Python
from typing import List
from google.cloud import storage
def set_bucket_public_iam(
bucket_name: str = "your-bucket-name",
members: List[str] = ["allUsers
):
Set a public IAM Policy to bucket
# bucket_name = "your-bucket-name"
storage_client = storage.Client()
bucket = storage_client.bucket(bucket_name)
policy = bucket.get_iam_policy(requested_policy_version=3)
policy.bindings.append(
{"role": "roles/storage.objectViewer", "members": members}
)
bucket.set_iam_policy(policy)
print(f"Bucket {bucket.name} is nowreadable")
## Ruby
def set_bucket_public_iam bucket_name:
# The ID of your GCS bucket
# bucket_name = "your-unique-bucket-name"
require "google/cloud/storage"
storage = Google::Cloud::Storage.new
bucket = storage.bucket bucket_name
bucket.policy do |p|
p.add "roles/storage.objectViewer", "allUsers"
end
puts "Bucket #{bucket_name} is nowreadable"
end
For more information, see the Cloud Storage C++ API reference documentation

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

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

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

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

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

 REST APIs
 JSON API
- Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials. For instructions, see API authentication

Create a JSON file that contains the following information:
{ "bindings { "role": "roles/storage.objectViewer", "membersallUsers"] } ] }
Use
cURLto call the JSON API with a
PUTBucket request:
curl -X PUT --data-binary @
JSON_FILE_NAME\ -H "Authorization: Bearer OAUTH2_TOKEN" \ -H "Content-Type: application/json" \ "httpsstorage.googleapis.com/storage/v1/b/ BUCKET_NAME/iam"
Where:
is the path for the JSON file that you created in Step 2

JSON_FILE_NAME
is the access token you created in Step 1

OAUTH2_TOKEN
is the name of the bucket whose objects you want to make public. For example,
BUCKET_NAME
my-bucket

-
 XML API
Making all objects in a bucketreadable is not supported by the XML API. Use gsutil or the JSON API instead

You can make groups of objects in your bucketaccessible, but generally, making all files in your bucketaccessible 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,
httpwww.example.com. For more information, see Website configuration examples

In the following sample, the
MainPageSuffix is set to
index.html and
NotFoundPage is set to
404.html:
 Console
- In the Google Cloud console, go to the Cloud Storage
Bucketspage

In the list of buckets, find the bucket you created

Click the
Bucket overflowmenu (
) associated with the bucket and select
Edit website configuration

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

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 gswww.example.com
If successful, the command returns:
Setting website config on gswww.example.com

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

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

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

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

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

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

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

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

## C++
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
gcs::Client client, std::string const&nbucket_name,
std::string const&nmain_page_suffix, std::string const&nnot_found_page) {
StatusOrusOrgcs::BucketMetadataPatchBuilderSetWebsite(
gcs::BucketWebsite{main_page_suffix, not_found_page
gcs::IfMetagenerationMatch(original->metageneration
if (!patched_metadata) {
throw std::runtime_error(patched_metadata.statusmessage
}
if (!patched_metadata->has_website {
std::cout <name() <<("\n";
return;
}
std::cout <name() <<("\nNew main page suffix is: "
<< patched_metadata->websitemain_page_suffix
<websitenot_found_page <public Bucket BucketWebsiteConfiguration(
string bucketName = "your-bucket-name",
string mainPageSuffix = "index.html",
string notFoundPage = "404.html")
{
var storage = StorageClient.Create
var bucket = storage.GetBucket(bucketName);
if (bucket.Website == null)
{
bucket.Website = new Bucket.WebsiteData
}
bucket.Website.MainPageSuffix = mainPageSuffix;
bucket.Website.NotFoundPage = notFoundPage;
bucket = storage.UpdateBucket(bucket);
Console.WriteLineStatic website bucket {bucketName} is set up to use {mainPageSuffix} as the index page and {notFoundPage} as the 404 not found page
return bucket;
}
}
## Go
import (
"context"
"fmt"
"io"
"time"
"cloud.google.com/go/storage"
)
// setBucketWebsiteInfo sets website configuration on a bucket

func setBucketWebsiteInfo(w io.Writer, bucketName, indexPage, notFoundPage string) error {
// bucketName := "www.example.com"
// indexPage := "index.html"
// notFoundPage := "404.html"
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()
bucket := client.Bucket(bucketName)
bucketAttrsToUpdate := storage.BucketAttrsToUpdate{
Website: &storage.BucketWebsite{
MainPageSuffix: indexPage,
NotFoundPage: notFoundPage,
},
}
if _, err := bucket.Update(ctx, bucketAttrsToUpdate); err != nil {
return fmt.Errorf("Bucket(%q).Update: %v", bucketName, err)
}
fmt.Fprintf(w, "Static website bucket %v is set up to use %v as the index page and %v as the 404 page\n", bucketName, indexPage, notFoundPage)
return nil
}
## Java
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.newBuildersetProjectId(projectId).buildgetService
Bucket bucket = storage.get(bucketName);
bucket.toBuildersetIndexPage(indexPage).setNotFoundPage(notFoundPage).buildupdate
System.out.println(
"Static website bucket "
+ bucketName
+ " is set up to use "
+ indexPage
+ " as the index page and "
+ notFoundPage
+ " as the 404 page
}
}
## Node.js

* TODO(developer): Uncomment the following lines before running the sample

*/
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';
// The name of the main page
// const mainPageSuffix = 'httpexample.com';
// The Name of a 404 page
// const notFoundPage = 'httpexample.com/404.html';
// Imports the Google Cloud client library
const {Storage} = requiregoogle-cloud/storage
// Creates a client
const storage = new Storage
async function addBucketWebsiteConfiguration() {
await storage.bucket(bucketName).setMetadata({
website: {
mainPageSuffix,
notFoundPage,
},

console.log(
`Static website bucket ${bucketName} is set up to use ${mainPageSuffix} as the index page and ${notFoundPage} as the 404 page`
);
}
addBucketWebsiteConfigurationcatch(console.error);
## PHP
use Google\Cloud\Storage\StorageClient;

* Update the given bucket's website configuration

*
* @param string $bucketName The name of your Cloud Storage bucket

* (e.g. 'my-bucket')
* @param string $indexPageObject the name of an object in the bucket to use as
* (e.g. 'index.html')
* an index page for a static website bucket

* @param string $notFoundPageObject the name of an object in the bucket to use
* (e.g. '404.html')
* as the 404 Not Found page

*/
function define_bucket_website_configuration(string $bucketName, string $indexPageObject, string $notFoundPageObject): void
{
$storage = new StorageClient
$bucket = $storage->bucket($bucketName);
$bucket->update([
'website' => [
'mainPageSuffix' => $indexPageObject,
'notFoundPage' => $notFoundPageObject
]

printf(
'Static website bucket %s is set up to use %s as the index page and %s as the 404 page
$bucketName,
$indexPageObject,
$notFoundPageObject
);
}
## Python
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
## Ruby
def define_bucket_website_configuration bucket_name:, main_page_suffix:, not_found_page:
# The ID of your static website bucket
# bucket_name = "www.example.com"
# The index page for a static website bucket
# main_page_suffix = "index.html"
# The 404 page for a static website bucket
# not_found_page = "404.html"
require "google/cloud/storage"
storage = Google::Cloud::Storage.new
bucket = storage.bucket bucket_name
bucket.update do |b|
b.website_main = main_page_suffix
b.website_404 = not_found_page
end
puts "Static website bucket #{bucket_name} is set up to use #{main_page_suffix} as the index page and " \
not_found_page} as the 404 page"
end
For more information, see the Cloud Storage C++ API reference documentation

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

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

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

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

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

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

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

 REST APIs
 JSON API
- Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials. For instructions, see API authentication

Create a JSON file that sets the
mainPageSuffixand
notFoundPageproperties in a
websiteobject to the desired pages:
{ "website "mainPageSuffix": "index.html", "notFoundPage": "404.html" } }
Use
cURLto call the JSON API with a
PATCHBucket 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" \ "httpsstorage.googleapis.com/storage/v1/b/www.example.com"
 XML API
- Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials. For instructions, see API authentication

Create an XML file that sets the
MainPageSuffixand
NotFoundPageelements in a
WebsiteConfigurationelement to the desired pages:
ges:
   request and
websiteConfigquery string parameter. For www.example.com:
curl -X PUT --data-binary @web-config.xml \ -H "Authorization: Bearer ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg" \ httpsstorage.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

## Clean up
After you finish the tutorial, you can clean up the resources that you created so that they stop using quota and incurring charges. 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:
-
In the Google Cloud console, go to the
Manage resourcespage

-
In the project list, select the project that you
want to delete, and then click
Delete

-
In the dialog, type the project ID, and then click
downto delete the project

## What's next
- See examples and tips for using buckets to host a static website

- Visit the troubleshooting section for hosting a static website

- Learn about hosting static assets for a dynamic website

- Go more in-depth with the Cloud Storage Office Hours for hosting a static website

- Learn about all web serving options

- Try other Google Cloud tutorials that use Cloud Storage.