Ospita un sito web statico


Questo tutorial descrive come configurare un bucket Cloud Storage per ospitare un sito web statico per un dominio di tua proprietà. Le pagine web statiche possono contenere tecnologie lato client come HTML, CSS e JavaScript. Non possono includere contenuti dinamici come script lato server come PHP.

Poiché Cloud Storage non supporta i domini personalizzati con HTTPS autonomamente, questo tutorial utilizza Cloud Storage con un Application Load Balancer esterno per gestire i contenuti di un dominio personalizzato tramite HTTPS. Per altri modi per pubblicare contenuti da un dominio personalizzato tramite HTTPS, consulta la risoluzione dei problemi relativi alla pubblicazione su HTTPS. Puoi anche utilizzare Cloud Storage per pubblicare contenuti di dominio personalizzati tramite HTTP, che non richiede un bilanciatore del carico.

Per esempi e suggerimenti sulle pagine web statiche, incluso come ospitare asset statici per un sito web dinamico, consulta la pagina Sito web statico.

Obiettivi

Questo tutorial ti mostra come:

  • Creare un bucket.
  • Carica e condividi i file del tuo sito.
  • Configura un bilanciatore del carico e un certificato SSL.
  • Connetti il bilanciatore del carico al bucket.
  • Punta il tuo dominio al bilanciatore del carico utilizzando un record A.
  • Testa il sito web.

Costi

Questo tutorial utilizza i seguenti componenti fatturabili di Google Cloud:

Consulta il suggerimento per il monitoraggio degli addebiti per i dettagli sugli addebiti che possono essere addebitati in caso di hosting di un sito web statico.

Prima di iniziare

  1. Accedi al tuo account Google Cloud. Se non conosci Google Cloud, crea un account per valutare le prestazioni dei nostri prodotti in scenari reali. I nuovi clienti ricevono anche 300 $di crediti gratuiti per l'esecuzione, il test e il deployment dei carichi di lavoro.
  2. Nella pagina del selettore di progetti della console Google Cloud, seleziona o crea un progetto Google Cloud.

    Vai al selettore progetti

  3. Assicurati che la fatturazione sia attivata per il tuo progetto Google Cloud.

  4. Nella pagina del selettore di progetti della console Google Cloud, seleziona o crea un progetto Google Cloud.

    Vai al selettore progetti

  5. Assicurati che la fatturazione sia attivata per il tuo progetto Google Cloud.

  6. Abilita l'API Compute Engine per il tuo progetto.
  7. Avere i seguenti ruoli di Identity and Access Management: Amministratore archiviazione e Amministratore rete Compute.
  8. Avere un dominio di tua proprietà o che gestisci. Se non hai un dominio esistente, esistono molti servizi tramite i quali puoi registrare un nuovo dominio, ad esempio Cloud Domains.

    Questo tutorial utilizza il dominio example.com.

  9. Hai alcuni file del sito web da pubblicare. Questo tutorial funziona al meglio se hai almeno una pagina di indice (index.html) e una pagina 404 (404.html).
  10. (Facoltativo) Se vuoi che il bucket Cloud Storage abbia lo stesso nome del tuo dominio, devi verificare che il dominio che utilizzerai sia di tua proprietà o che gestisci tu. Assicurati di verificare il dominio di primo livello, come example.com, e non un sottodominio, come www.example.com. Se hai acquistato il tuo dominio tramite Cloud Domains, la verifica è automatica.

crea un bucket

Per creare un bucket:

Console

  1. Nella console Google Cloud, vai alla pagina Bucket di Cloud Storage.

    Vai a Bucket

  2. Fai clic su + Crea.
  3. Nella pagina Crea un bucket, inserisci le informazioni del bucket. Per andare al passaggio successivo, fai clic su Continua.
    • In Assegna un nome al bucket, inserisci un nome che soddisfi i requisiti per i nomi dei bucket.
    • Per Scegli dove archiviare i tuoi dati, seleziona un tipo di località e una località in cui verranno archiviati definitivamente i dati del bucket.
    • In Scegli una classe di archiviazione per i tuoi dati, seleziona una classe di archiviazione predefinita per il bucket oppure Autoclass per la gestione automatica della classe di archiviazione dei dati del bucket.

      Nota:il riquadro Stima del costo mensile nel riquadro di destra stima i costi mensili del bucket in base alla classe di archiviazione e alla località selezionate, nonché alle dimensioni e alle operazioni previste per i dati.

    • Per Scegli come controllare l'accesso agli oggetti, scegli se il bucket deve applicare o meno la prevenzione dell'accesso pubblico e seleziona un modello di controllo dell'accesso per gli oggetti del bucket.

      Nota: se la prevenzione dell'accesso pubblico è già applicata dal criterio dell'organizzazione del progetto, l'opzione di attivazione/disattivazione Impedisci l'accesso pubblico è bloccata.

    • Per Scegli come proteggere i dati degli oggetti, se vuoi configura Strumenti di protezione e seleziona un metodo di crittografia dei dati.
  4. Fai clic su Crea.

Per scoprire come ottenere informazioni dettagliate sugli errori relativi alle operazioni di Cloud Storage non riuscite nella console Google Cloud, consulta Risoluzione dei problemi.

Riga di comando

  1. Nella console Google Cloud, attiva Cloud Shell.

    Attiva Cloud Shell

    Nella parte inferiore della console Google Cloud viene avviata una sessione di Cloud Shell che mostra un prompt della riga di comando. Cloud Shell è un ambiente shell con Google Cloud CLI già installato e con valori già impostati per il progetto attuale. L'inizializzazione della sessione può richiedere alcuni secondi.

  2. Nel tuo ambiente di sviluppo, esegui il comando gcloud storage buckets create:

    gcloud storage buckets create gs://BUCKET_NAME --location=BUCKET_LOCATION

    Dove:

    • BUCKET_NAME è il nome che vuoi assegnare al bucket, soggetto ai requisiti di denominazione. Ad esempio, my-bucket.
    • BUCKET_LOCATION è la località del bucket. Ad esempio: us-east1.

    Se la richiesta ha esito positivo, il comando restituisce il seguente messaggio:

    Creating gs://BUCKET_NAME/...

    Imposta i flag seguenti per avere un maggiore controllo sulla creazione del bucket:

    • --project: specifica l'ID o il numero del progetto a cui sarà associato il bucket. Ad esempio, my-project.
    • --default-storage-class: specifica la classe di archiviazione predefinita del tuo bucket. Ad esempio: STANDARD.
    • --soft-delete-duration: specifica la durata di conservazione per l'eliminazione temporanea del tuo bucket. Ad esempio: 2w1d.
    • --uniform-bucket-level-access: abilita l'accesso uniforme a livello di bucket per il bucket.
    • Per un elenco completo delle opzioni per la creazione dei bucket gcloud, vedi le opzioni di buckets create.

    Ad esempio:

    gcloud storage buckets create gs://BUCKET_NAME --project=PROJECT_ID --default-storage-class=STORAGE_CLASS --location=BUCKET_LOCATION --uniform-bucket-level-access

Librerie client

C++

Per maggiori informazioni, consulta la documentazione di riferimento dell'API C++ di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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<gcs::BucketMetadata> bucket_metadata =
      client.CreateBucket(bucket_name, gcs::BucketMetadata()
                                           .set_storage_class(storage_class)
                                           .set_location(location));
  if (!bucket_metadata) throw std::move(bucket_metadata).status();

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

C#

Per maggiori informazioni, consulta la documentazione di riferimento dell'API C# di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.


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

public class CreateRegionalBucketSample
{
    /// <summary>
    /// Creates a storage bucket with region.
    /// </summary>
    /// <param name="projectId">The ID of the project to create the buckets in.</param>
    /// <param name="location">The location of the bucket. Object data for objects in the bucket resides in
    /// physical storage within this region. Defaults to US.</param>
    /// <param name="bucketName">The name of the bucket to create.</param>
    /// <param name="storageClass">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
    /// STANDARD.</param>
    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.WriteLine($"Created {bucketName}.");
        return newlyCreatedBucket;
    }
}

Go

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Go di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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: %w", 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: %w", bucketName, err)
	}
	fmt.Fprintf(w, "Created bucket %v in %v with storage class %v\n", bucketName, storageClassAndLocation.Location, storageClassAndLocation.StorageClass)
	return nil
}

Java

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Java di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Node.js di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

/**
 * 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:
// https://googleapis.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:
// http://g.co/cloud/storage/docs/locations#location-mr
// const location = 'ASIA';

// Imports the Google Cloud client library
const {Storage} = require('@google-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 https://cloud.google.com/docs/authentication/production or https://googleapis.dev/nodejs/storage/latest/Storage.html
const storage = new Storage();

async function createBucketWithStorageClassAndLocation() {
  // 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,
    [storageClass]: true,
  });

  console.log(
    `${bucket.name} created with ${storageClass} class in ${location}`
  );
}

createBucketWithStorageClassAndLocation().catch(console.error);

PHP

Per maggiori informazioni, consulta la documentazione di riferimento dell'API PHP di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Python di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Ruby di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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

Terraform

Puoi utilizzare una risorsa Terraform per creare un bucket di archiviazione.

L'esempio seguente include l'assegnazione di un suffisso della pagina di indice e di una pagina di errore personalizzata. Per ulteriori informazioni, consulta la sezione Assegnare pagine speciali.

# Create new storage bucket in the US multi-region
# and settings for main_page_suffix and not_found_page
resource "random_id" "bucket_prefix" {
  byte_length = 8
}

resource "google_storage_bucket" "static_website" {
  name          = "${random_id.bucket_prefix.hex}-static-website-bucket"
  location      = "US"
  storage_class = "STANDARD"
  website {
    main_page_suffix = "index.html"
    not_found_page   = "404.html"
  }
}

API REST

API JSON

  1. Assicurati che gcloud CLI sia installato e inizializzatoper generare un token di accesso per l'intestazione Authorization.

    In alternativa, puoi creare un token di accesso utilizzando OAuth 2.0 Playground e includerlo nell'intestazione Authorization.

  2. Crea un file JSON contenente le impostazioni per il bucket, che deve includere un valore name per il bucket. Consulta la documentazione relativa a Buckets:Insert per un elenco completo delle impostazioni. Di seguito sono riportate le impostazioni più comuni da includere:
  3. {
      "name": "BUCKET_NAME",
      "location": "BUCKET_LOCATION",
      "storageClass": "STORAGE_CLASS",
      "iamConfiguration": {
        "uniformBucketLevelAccess": {
          "enabled": true
        },
      }
    }

    Dove:

  4. Utilizza cURL per chiamare l'API JSON:
    curl -X POST --data-binary @JSON_FILE_NAME \
         -H "Authorization: Bearer $(gcloud auth print-access-token)" \
         -H "Content-Type: application/json" \
         "https://storage.googleapis.com/storage/v1/b?project=PROJECT_IDENTIFIER"

    Dove:

    • JSON_FILE_NAME è il nome del file JSON che hai creato nel passaggio 2.
    • PROJECT_IDENTIFIER è l'ID o il numero del progetto a cui sarà associato il tuo bucket. Ad esempio, my-project.

API XML

  1. Assicurati che gcloud CLI sia installato e inizializzatoper generare un token di accesso per l'intestazione Authorization.

    In alternativa, puoi creare un token di accesso utilizzando OAuth 2.0 Playground e includerlo nell'intestazione Authorization.

  2. Crea un file XML contenente le impostazioni per il bucket. Consulta la documentazione XML: Create a bucket per un elenco completo delle impostazioni. Di seguito sono riportate le impostazioni più comuni da includere:
  3. <CreateBucketConfiguration>
       <LocationConstraint>BUCKET_LOCATION</LocationConstraint>
       <StorageClass>STORAGE_CLASS</StorageClass>
    </CreateBucketConfiguration>

    Dove:

  4. Utilizza cURL per chiamare l'API XML:
    curl -X PUT --data-binary @XML_FILE_NAME \
         -H "Authorization: Bearer $(gcloud auth print-access-token)" \
         -H "x-goog-project-id: PROJECT_ID" \
         "https://storage.googleapis.com/BUCKET_NAME"

    Dove:

    • XML_FILE_NAME è il nome del file XML che hai creato nel passaggio 2.
    • PROJECT_ID è l'ID del progetto a cui verrà associato il bucket. Ad esempio, my-project.
    • BUCKET_NAME è il nome che vuoi assegnare al bucket, soggetto ai requisiti di denominazione. Ad esempio: my-bucket.

Carica i file del tuo sito

Aggiungi al bucket i file che vuoi che il tuo sito web pubblichi:

Console

  1. Nella console Google Cloud, vai alla pagina Bucket di Cloud Storage.

    Vai a Bucket

  2. Nell'elenco dei bucket, fai clic sul nome del bucket che hai creato.

    Si apre la pagina Dettagli bucket in cui è selezionata la scheda Oggetti.

  3. Fai clic sul pulsante Carica file.

  4. Nella finestra di dialogo del file, sfoglia il file e selezionalo.

Al termine del caricamento, nel bucket dovrebbero essere visualizzati il nome e le informazioni sul file.

Per scoprire come ottenere informazioni dettagliate sugli errori relativi alle operazioni di Cloud Storage non riuscite nella console Google Cloud, consulta Risoluzione dei problemi.

Riga di comando

Utilizza il comando gcloud storage cp per copiare i file nel bucket. Ad esempio, per copiare il file index.html dalla posizione attuale Desktop nel bucket my-static-assets:

gcloud storage cp Desktop/index.html gs://my-static-assets

Se l'esito è positivo, la risposta sarà simile al seguente esempio:

Completed files 1/1 | 164.3kiB/164.3kiB

Librerie client

C++

Per maggiori informazioni, consulta la documentazione di riferimento dell'API C++ di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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::move(metadata).status();

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

C#

Per maggiori informazioni, consulta la documentazione di riferimento dell'API C# di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.


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.WriteLine($"Uploaded {objectName}.");
    }
}

Go

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Go di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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: %w", err)
	}
	defer client.Close()

	// Open local file.
	f, err := os.Open("notes.txt")
	if err != nil {
		return fmt.Errorf("os.Open: %w", 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: %w", 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: %w", err)
	}
	if err := wc.Close(); err != nil {
		return fmt.Errorf("Writer.Close: %w", err)
	}
	fmt.Fprintf(w, "Blob %v uploaded.\n", object)
	return nil
}

Java

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Java di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.


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.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();

    // 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.
    Storage.BlobWriteOption precondition;
    if (storage.get(bucketName, objectName) == null) {
      // For a target object that does not yet exist, set the DoesNotExist precondition.
      // This will cause the request to fail if the object is created before the request runs.
      precondition = Storage.BlobWriteOption.doesNotExist();
    } else {
      // If the destination already exists in your bucket, instead set a generation-match
      // precondition. This will cause the request to fail if the existing object's generation
      // changes before the request runs.
      precondition =
          Storage.BlobWriteOption.generationMatch(
              storage.get(bucketName, objectName).getGeneration());
    }
    storage.createFrom(blobInfo, Paths.get(filePath), precondition);

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

Node.js

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Node.js di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

Nell'esempio seguente viene caricato un singolo oggetto:

/**
 * 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} = require('@google-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.log(`${filePath} uploaded to ${bucketName}`);
}

uploadFile().catch(console.error);

Il seguente esempio carica più oggetti contemporaneamente:

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// The ID of the first GCS file to download
// const firstFilePath = 'your-first-file-name';

// The ID of the second GCS file to download
// const secondFilePath = 'your-second-file-name';

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

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

// Creates a transfer manager client
const transferManager = new TransferManager(storage.bucket(bucketName));

async function uploadManyFilesWithTransferManager() {
  // Uploads the files
  await transferManager.uploadManyFiles([firstFilePath, secondFilePath]);

  for (const filePath of [firstFilePath, secondFilePath]) {
    console.log(`${filePath} uploaded to ${bucketName}.`);
  }
}

uploadManyFilesWithTransferManager().catch(console.error);

L'esempio seguente carica contemporaneamente tutti gli oggetti con un prefisso comune:

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// The local directory to upload
// const directoryName = 'your-directory';

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

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

// Creates a transfer manager client
const transferManager = new TransferManager(storage.bucket(bucketName));

async function uploadDirectoryWithTransferManager() {
  // Uploads the directory
  await transferManager.uploadManyFiles(directoryName);

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

uploadDirectoryWithTransferManager().catch(console.error);

PHP

Per maggiori informazioni, consulta la documentazione di riferimento dell'API PHP di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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();
    if (!$file = fopen($source, 'r')) {
        throw new \InvalidArgumentException('Unable to open file for reading');
    }
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->upload($file, [
        'name' => $objectName
    ]);
    printf('Uploaded %s to gs://%s/%s' . PHP_EOL, basename($source), $bucketName, $objectName);
}

Python

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Python di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

Nell'esempio seguente viene caricato un singolo oggetto:

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)

    # 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 if_generation_match precondition to 0.
    # If the destination object already exists in your bucket, set instead a
    # generation-match precondition using its generation number.
    generation_match_precondition = 0

    blob.upload_from_filename(source_file_name, if_generation_match=generation_match_precondition)

    print(
        f"File {source_file_name} uploaded to {destination_blob_name}."
    )

Il seguente esempio carica più oggetti contemporaneamente:

def upload_many_blobs_with_transfer_manager(
    bucket_name, filenames, source_directory="", workers=8
):
    """Upload every file in a list to a bucket, concurrently in a process pool.

    Each blob name is derived from the filename, not including the
    `source_directory` parameter. For complete control of the blob name for each
    file (and other aspects of individual blob metadata), use
    transfer_manager.upload_many() instead.
    """

    # The ID of your GCS bucket
    # bucket_name = "your-bucket-name"

    # A list (or other iterable) of filenames to upload.
    # filenames = ["file_1.txt", "file_2.txt"]

    # The directory on your computer that is the root of all of the files in the
    # list of filenames. This string is prepended (with os.path.join()) to each
    # filename to get the full path to the file. Relative paths and absolute
    # paths are both accepted. This string is not included in the name of the
    # uploaded blob; it is only used to find the source files. An empty string
    # means "the current working directory". Note that this parameter allows
    # directory traversal (e.g. "/", "../") and is not intended for unsanitized
    # end user input.
    # source_directory=""

    # The maximum number of processes to use for the operation. The performance
    # impact of this value depends on the use case, but smaller files usually
    # benefit from a higher number of processes. Each additional process occupies
    # some CPU and memory resources until finished. Threads can be used instead
    # of processes by passing `worker_type=transfer_manager.THREAD`.
    # workers=8

    from google.cloud.storage import Client, transfer_manager

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

    results = transfer_manager.upload_many_from_filenames(
        bucket, filenames, source_directory=source_directory, max_workers=workers
    )

    for name, result in zip(filenames, results):
        # The results list is either `None` or an exception for each filename in
        # the input list, in order.

        if isinstance(result, Exception):
            print("Failed to upload {} due to exception: {}".format(name, result))
        else:
            print("Uploaded {} to {}.".format(name, bucket.name))

L'esempio seguente carica contemporaneamente tutti gli oggetti con un prefisso comune:

def upload_directory_with_transfer_manager(bucket_name, source_directory, workers=8):
    """Upload every file in a directory, including all files in subdirectories.

    Each blob name is derived from the filename, not including the `directory`
    parameter itself. For complete control of the blob name for each file (and
    other aspects of individual blob metadata), use
    transfer_manager.upload_many() instead.
    """

    # The ID of your GCS bucket
    # bucket_name = "your-bucket-name"

    # The directory on your computer to upload. Files in the directory and its
    # subdirectories will be uploaded. An empty string means "the current
    # working directory".
    # source_directory=""

    # The maximum number of processes to use for the operation. The performance
    # impact of this value depends on the use case, but smaller files usually
    # benefit from a higher number of processes. Each additional process occupies
    # some CPU and memory resources until finished. Threads can be used instead
    # of processes by passing `worker_type=transfer_manager.THREAD`.
    # workers=8

    from pathlib import Path

    from google.cloud.storage import Client, transfer_manager

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

    # Generate a list of paths (in string form) relative to the `directory`.
    # This can be done in a single list comprehension, but is expanded into
    # multiple lines here for clarity.

    # First, recursively get all files in `directory` as Path objects.
    directory_as_path_obj = Path(source_directory)
    paths = directory_as_path_obj.rglob("*")

    # Filter so the list only includes files, not directories themselves.
    file_paths = [path for path in paths if path.is_file()]

    # These paths are relative to the current working directory. Next, make them
    # relative to `directory`
    relative_paths = [path.relative_to(source_directory) for path in file_paths]

    # Finally, convert them all to strings.
    string_paths = [str(path) for path in relative_paths]

    print("Found {} files.".format(len(string_paths)))

    # Start the upload.
    results = transfer_manager.upload_many_from_filenames(
        bucket, string_paths, source_directory=source_directory, max_workers=workers
    )

    for name, result in zip(string_paths, results):
        # The results list is either `None` or an exception for each filename in
        # the input list, in order.

        if isinstance(result, Exception):
            print("Failed to upload {} due to exception: {}".format(name, result))
        else:
            print("Uploaded {} to {}.".format(name, bucket.name))

Ruby

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Ruby di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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

Terraform

# Upload a simple index.html page to the bucket
resource "google_storage_bucket_object" "indexpage" {
  name         = "index.html"
  content      = "<html><body>Hello World!</body></html>"
  content_type = "text/html"
  bucket       = google_storage_bucket.static_website.id
}

# Upload a simple 404 / error page to the bucket
resource "google_storage_bucket_object" "errorpage" {
  name         = "404.html"
  content      = "<html><body>404!</body></html>"
  content_type = "text/html"
  bucket       = google_storage_bucket.static_website.id
}

API REST

API JSON

  1. Assicurati che gcloud CLI sia installato e inizializzatoper generare un token di accesso per l'intestazione Authorization.

    In alternativa, puoi creare un token di accesso utilizzando OAuth 2.0 Playground e includerlo nell'intestazione Authorization.

  2. Utilizza cURL per chiamare l'API JSON con una richiesta POST oggetto. Per il file index.html caricato in un bucket denominato my-static-assets:

    curl -X POST --data-binary @index.html \
      -H "Content-Type: text/html" \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      "https://storage.googleapis.com/upload/storage/v1/b/my-static-assets/o?uploadType=media&name=index.html"

API XML

  1. Assicurati che gcloud CLI sia installato e inizializzatoper generare un token di accesso per l'intestazione Authorization.

    In alternativa, puoi creare un token di accesso utilizzando OAuth 2.0 Playground e includerlo nell'intestazione Authorization.

  2. Utilizza cURL per chiamare l'API XML con una richiesta PUT oggetto. Per il file index.html caricato in un bucket denominato my-static-assets:

    curl -X PUT --data-binary @index.html \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: text/html" \
      "https://storage.googleapis.com/my-static-assets/index.html"

Condividi i tuoi file

Per rendere leggibili tutti gli oggetti nel bucket a chiunque su internet:

Console

  1. Nella console Google Cloud, vai alla pagina Bucket di Cloud Storage.

    Vai a Bucket

  2. Nell'elenco dei bucket, fai clic sul nome del bucket che vuoi rendere pubblico.

  3. Seleziona la scheda Autorizzazioni nella parte superiore della pagina.

  4. Se nel riquadro Accesso pubblico è indicato Non pubblico, fai clic sul pulsante Rimuovi prevenzione accesso pubblico e fai clic su Conferma nella finestra di dialogo visualizzata.

  5. Fai clic sul pulsante Concedi l'accesso.

    Viene visualizzata la finestra di dialogo Aggiungi entità.

  6. Nel campo Nuove entità, inserisci allUsers.

  7. Nel menu a discesa Seleziona un ruolo, seleziona il sottomenu Cloud Storage e fai clic sull'opzione Visualizzatore oggetti Storage.

  8. Fai clic su Salva.

  9. Fai clic su Consenti accesso pubblico.

Una volta condiviso pubblicamente, viene visualizzata un'icona link per ogni oggetto nella colonna Accesso pubblico. Puoi fare clic su questa icona per ottenere l'URL dell'oggetto.

Per scoprire come ottenere informazioni dettagliate sugli errori relativi alle operazioni di Cloud Storage non riuscite nella console Google Cloud, consulta Risoluzione dei problemi.

Riga di comando

Utilizza il comando buckets add-iam-policy-binding:

gcloud storage buckets add-iam-policy-binding  gs://my-static-assets --member=allUsers --role=roles/storage.objectViewer

Librerie client

C++

Per maggiori informazioni, consulta la documentazione di riferimento dell'API C++ di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
  auto current_policy = client.GetNativeBucketIamPolicy(
      bucket_name, gcs::RequestedPolicyVersion(3));
  if (!current_policy) throw std::move(current_policy).status();

  current_policy->set_version(3);
  current_policy->bindings().emplace_back(
      gcs::NativeIamBinding("roles/storage.objectViewer", {"allUsers"}));

  auto updated =
      client.SetNativeBucketIamPolicy(bucket_name, *current_policy);
  if (!updated) throw std::move(updated).status();

  std::cout << "Policy successfully updated: " << *updated << "\n";
}

C#

Per maggiori informazioni, consulta la documentazione di riferimento dell'API C# di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.


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

public class MakeBucketPublicSample
{
    public void MakeBucketPublic(string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();

        Policy policy = storage.GetBucketIamPolicy(bucketName);

        policy.Bindings.Add(new Policy.BindingsData
        {
            Role = "roles/storage.objectViewer",
            Members = new List<string> { "allUsers" }
        });

        storage.SetBucketIamPolicy(bucketName, policy);
        Console.WriteLine(bucketName + " is now public ");
    }
}

Go

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Go di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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 bucket publicly readable.
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: %w", err)
	}
	defer client.Close()

	policy, err := client.Bucket(bucketName).IAM().V3().Policy(ctx)
	if err != nil {
		return fmt.Errorf("Bucket(%q).IAM().V3().Policy: %w", bucketName, err)
	}
	role := "roles/storage.objectViewer"
	policy.Bindings = append(policy.Bindings, &iampb.Binding{
		Role:    role,
		Members: []string{iam.AllUsers},
	})
	if err := client.Bucket(bucketName).IAM().V3().SetPolicy(ctx, policy); err != nil {
		return fmt.Errorf("Bucket(%q).IAM().SetPolicy: %w", bucketName, err)
	}
	fmt.Fprintf(w, "Bucket %v is now publicly readable\n", bucketName)
	return nil
}

Java

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Java di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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");
  }
}

Node.js

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Node.js di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

/**
 * 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} = require('@google-cloud/storage');

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

async function makeBucketPublic() {
  await storage.bucket(bucketName).makePublic();

  console.log(`Bucket ${bucketName} is now publicly readable`);
}

makeBucketPublic().catch(console.error);

PHP

Per maggiori informazioni, consulta la documentazione di riferimento dell'API PHP di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

use Google\Cloud\Storage\StorageClient;

/**
 * Update the specified bucket's IAM configuration to make it publicly accessible.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function set_bucket_public_iam(string $bucketName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);

    $policy = $bucket->iam()->policy(['requestedPolicyVersion' => 3]);
    $policy['version'] = 3;

    $role = 'roles/storage.objectViewer';
    $members = ['allUsers'];

    $policy['bindings'][] = [
        'role' => $role,
        'members' => $members
    ];

    $bucket->iam()->setPolicy($policy);

    printf('Bucket %s is now public', $bucketName);
}

Python

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Python di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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 now publicly readable")

Ruby

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Ruby di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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 now publicly readable"
end

Terraform

# Make bucket public by granting allUsers READER access
resource "google_storage_bucket_access_control" "public_rule" {
  bucket = google_storage_bucket.static_website.id
  role   = "READER"
  entity = "allUsers"
}

API REST

API JSON

  1. Assicurati che gcloud CLI sia installato e inizializzatoper generare un token di accesso per l'intestazione Authorization.

    In alternativa, puoi creare un token di accesso utilizzando OAuth 2.0 Playground e includerlo nell'intestazione Authorization.

  2. Crea un file JSON contenente le seguenti informazioni:

    {
      "bindings":[
        {
          "role": "roles/storage.objectViewer",
          "members":["allUsers"]
        }
      ]
    }
  3. Utilizza cURL per chiamare l'API JSON con una richiesta PUT di bucket:

    curl -X PUT --data-binary @JSON_FILE_NAME \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/iam"

    Dove:

    • JSON_FILE_NAME è il percorso del file JSON creato nel passaggio 2.
    • BUCKET_NAME è il nome del bucket di cui vuoi rendere pubblici gli oggetti. Ad esempio, my-static-assets.

API XML

L'API XML non supporta la lettura pubblica di tutti gli oggetti in un bucket. Utilizza la console Google Cloud o gcloud storage oppure imposta gli ACL per ogni singolo oggetto.

Per rendere accessibili pubblicamente ai singoli oggetti nel bucket, devi impostare la modalità di Controllo dell'accesso del bucket su Granulare. In genere, rendere tutti i file nel tuo bucket accessibili pubblicamente è più semplice e veloce.

I visitatori ricevono un codice di risposta http 403 quando richiedono l'URL di un file non pubblico o inesistente. Consulta la sezione successiva per informazioni su come aggiungere una pagina di errore che utilizza un codice di risposta http 404.

Consigliato: assegna pagine speciali

Puoi assegnare un suffisso della pagina di indice e una pagina di errore personalizzata, note come pagine di specialità. L'assegnazione è facoltativa, ma se non assegni un suffisso della pagina di indice e non carichi la pagina di indice corrispondente, agli utenti che accedono al sito di primo livello verrà mostrata una struttura di documenti XML contenente un elenco degli oggetti pubblici presenti nel tuo bucket.

Per ulteriori informazioni sul comportamento delle pagine specializzate, consulta la sezione Pagine speciali.

Console

  1. Nella console Google Cloud, vai alla pagina Bucket di Cloud Storage.

    Vai a Bucket

  2. Nell'elenco dei bucket, individua il bucket che hai creato.

  3. Fai clic sul menu overflow del bucket () associato al bucket e seleziona Modifica configurazione sito web.

  4. Nella finestra di dialogo di configurazione del sito web, specifica la pagina principale e la pagina di errore.

  5. Fai clic su Salva.

Per scoprire come ottenere informazioni dettagliate sugli errori relativi alle operazioni di Cloud Storage non riuscite nella console Google Cloud, consulta Risoluzione dei problemi.

Riga di comando

Utilizza il comando buckets update con i flag --web-main-page-suffix e --web-error-page.

Nel seguente esempio, MainPageSuffix è impostato su index.html e NotFoundPage è impostato su 404.html:

gcloud storage buckets update gs://my-static-assets --web-main-page-suffix=index.html --web-error-page=404.html

In caso di esito positivo, il comando restituisce:

Updating gs://www.example.com/...
  Completed 1

Librerie client

C++

Per maggiori informazioni, consulta la documentazione di riferimento dell'API C++ di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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::move(original).status();
  StatusOr<gcs::BucketMetadata> patched = client.PatchBucket(
      bucket_name,
      gcs::BucketMetadataPatchBuilder().SetWebsite(
          gcs::BucketWebsite{main_page_suffix, not_found_page}),
      gcs::IfMetagenerationMatch(original->metageneration()));
  if (!patched) throw std::move(patched).status();

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

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

C#

Per maggiori informazioni, consulta la documentazione di riferimento dell'API C# di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.


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

public class BucketWebsiteConfigurationSample
{
    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.WriteLine($"Static website bucket {bucketName} is set up to use {mainPageSuffix} as the index page and {notFoundPage} as the 404 not found page.");
        return bucket;
    }
}

Go

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Go di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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: %w", 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: %w", 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

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Java di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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");
  }
}

Node.js

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Node.js di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

/**
 * 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 = 'http://example.com';

// The Name of a 404 page
// const notFoundPage = 'http://example.com/404.html';

// Imports the Google Cloud client library
const {Storage} = require('@google-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`
  );
}

addBucketWebsiteConfiguration().catch(console.error);

PHP

Per maggiori informazioni, consulta la documentazione di riferimento dell'API PHP di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Python di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Ruby di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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

API REST

API JSON

  1. Assicurati che gcloud CLI sia installato e inizializzatoper generare un token di accesso per l'intestazione Authorization.

    In alternativa, puoi creare un token di accesso utilizzando OAuth 2.0 Playground e includerlo nell'intestazione Authorization.

  2. Crea un file JSON che imposta le proprietà mainPageSuffix e notFoundPage in un oggetto website sulle pagine desiderate.

    Nel seguente esempio, mainPageSuffix è impostato su index.html e notFoundPage è impostato su 404.html:

    {
      "website":{
        "mainPageSuffix": "index.html",
        "notFoundPage": "404.html"
      }
    }
  3. Utilizza cURL per chiamare l'API JSON con una richiesta di PATCH bucket. Per il bucket my-static-assets:

    curl -X PATCH --data-binary @web-config.json \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://storage.googleapis.com/storage/v1/b/my-static-assets"

API XML

  1. Assicurati che gcloud CLI sia installato e inizializzatoper generare un token di accesso per l'intestazione Authorization.

    In alternativa, puoi creare un token di accesso utilizzando OAuth 2.0 Playground e includerlo nell'intestazione Authorization.

  2. Crea un file XML che imposti gli elementi MainPageSuffix e NotFoundPage in un elemento WebsiteConfiguration sulle pagine desiderate.

    Nel seguente esempio, MainPageSuffix è impostato su index.html e NotFoundPage è impostato su 404.html:

    <WebsiteConfiguration>
      <MainPageSuffix>index.html</MainPageSuffix>
      <NotFoundPage>404.html</NotFoundPage>
    </WebsiteConfiguration>
  3. Utilizza cURL per chiamare l'API XML con una richiesta PUT di bucket e un parametro della stringa di query websiteConfig. Per my-static-assets:

    curl -X PUT --data-binary @web-config.xml \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      https://storage.googleapis.com/my-static-assets?websiteConfig

Configura il bilanciatore del carico e il certificato SSL

Cloud Storage non supporta i domini personalizzati con HTTPS autonomamente, perciò devi anche configurare un certificato SSL collegato a un bilanciatore del carico HTTPS per gestire il sito web tramite HTTPS. Questa sezione mostra come aggiungere il bucket al backend di un bilanciatore del carico e come aggiungere un nuovo certificato SSL gestito da Google al frontend del bilanciatore del carico.

Avvia la configurazione

  1. Nella console Google Cloud, vai alla pagina Bilanciamento del carico.

    Vai a Bilanciamento del carico

  2. Fai clic su Crea bilanciatore del carico.
  3. In Tipo di bilanciatore del carico, seleziona Bilanciatore del carico delle applicazioni (HTTP/HTTPS) e fai clic su Avanti.
  4. In Pubblico o interno, seleziona Per il pubblico (esterno) e fai clic su Avanti.
  5. In Deployment a regione singola o globale, seleziona Ideale per carichi di lavoro globali e fai clic su Avanti.
  6. In Generazione del bilanciatore del carico, seleziona Bilanciatore del carico delle applicazioni classico e fai clic su Avanti.
  7. Fai clic su Configura.

Viene visualizzata la finestra di configurazione del bilanciatore del carico.

Configurazione di base

Prima di continuare con la configurazione, inserisci un Nome del bilanciatore del carico, ad esempio example-lb.

Configura il frontend

Questa sezione mostra come configurare il protocollo HTTPS e creare un certificato SSL. Puoi anche selezionare un certificato esistente o caricare un certificato SSL autogestito.

  1. Fai clic su Configurazione frontend.
  2. (Facoltativo) Assegna un nome alla configurazione del frontend.
  3. In Protocollo, seleziona HTTPS (include HTTP/2).
  4. Per Versione IP, seleziona IPv4. Se preferisci IPv6, consulta la pagina relativa alla terminazione IPv6 per ulteriori informazioni.
  5. Per il campo Indirizzo IP:

    • Nel menu a discesa, fai clic su Crea indirizzo IP.
    • Nella finestra popup Prenota un nuovo indirizzo IP statico, inserisci un nome, ad esempio example-ip, per il Nome dell'indirizzo IP.
    • Fai clic su Prenota.
  6. In corrispondenza di Porta, seleziona 443.

  7. Nel menu a discesa del campo Certificato, seleziona Crea un nuovo certificato. Il modulo di creazione del certificato viene visualizzato in un riquadro. Configura quanto segue:

    • Assegna un nome al certificato, ad esempio example-ssl.
    • In Modalità di creazione, seleziona Crea certificato gestito da Google.
    • In Domini, inserisci il nome del tuo sito web, ad esempio www.example.com. Se vuoi pubblicare i tuoi contenuti tramite domini aggiuntivi come il dominio principale example.com, premi Invio per aggiungerli su altre righe. Ogni certificato ha un limite di domini 100.
  8. Fai clic su Crea.

  9. (Facoltativo) Se vuoi che Google Cloud configuri automaticamente un bilanciatore del carico HTTP parziale per il reindirizzamento del traffico HTTP, seleziona la casella di controllo accanto ad Abilita reindirizzamento da HTTP a HTTPS.

  10. Fai clic su Fine.

Configura il backend

  1. Fai clic su Configurazione backend.
  2. Nel menu a discesa Servizi e bucket di backend, fai clic su Crea un bucket di backend.
  3. Scegli un Nome bucket di backend, ad esempio example-bucket. Il nome che scegli può essere diverso dal nome del bucket che hai creato in precedenza.
  4. Fai clic su Sfoglia nel campo Bucket Cloud Storage.
  5. Seleziona il bucket my-static-assets che hai creato in precedenza e fai clic su Seleziona.
  6. (Facoltativo) Se vuoi utilizzare Cloud CDN, seleziona la casella di controllo Abilita Cloud CDN e configura Cloud CDN in base alle tue esigenze. Tieni presente che Cloud CDN può comportare costi aggiuntivi.
  7. Fai clic su Crea.

Configura le regole di routing

Le regole di routing sono i componenti della mappa URL di un bilanciatore del carico delle applicazioni esterno. Per questo tutorial, dovresti saltare questa parte della configurazione del bilanciatore del carico, poiché è impostata automaticamente per l'utilizzo del backend appena configurato.

Rivedi la configurazione

  1. Fai clic su Esamina e finalizza.
  2. Esamina Frontend, Regole di routing e Backend.
  3. Fai clic su Crea.

Potresti dover attendere qualche minuto per la creazione del bilanciatore del carico.

Connetti il tuo dominio al bilanciatore del carico

Dopo aver creato il bilanciatore del carico, fai clic sul nome del bilanciatore del carico: example-lb. Prendi nota dell'indirizzo IP associato al bilanciatore del carico: ad esempio, 30.90.80.100. Per puntare il tuo dominio al bilanciatore del carico, crea un record A utilizzando il servizio di registrazione del dominio. Se hai aggiunto più domini al certificato SSL, devi aggiungere un record A per ciascuno, tutti che puntano all'indirizzo IP del bilanciatore del carico. Ad esempio, per creare i record A per www.example.com e example.com:

NAME                  TYPE     DATA
www                   A        30.90.80.100
@                     A        30.90.80.100

Google Cloud potrebbe impiegare fino a 60-90 minuti per eseguire il provisioning del certificato e rendere il sito disponibile tramite il bilanciatore del carico. Per monitorare lo stato del certificato:

Console

  1. Vai alla pagina Bilanciamento del carico nella console Google Cloud.
    Vai a Bilanciamento del carico
  2. Fai clic sul nome del bilanciatore del carico: example-lb.
  3. Fai clic sul nome del certificato SSL associato al bilanciatore del carico: example-ssl.
  4. Le righe Stato e Stato del dominio mostrano lo stato del certificato. Devono essere attivi entrambi affinché il certificato sia valido per il tuo sito web.

Riga di comando

  1. Per controllare lo stato del certificato, esegui questo comando:

    gcloud compute ssl-certificates describe CERTIFICATE_NAME \
      --global \
      --format="get(name,managed.status)"
    
  2. Per controllare lo stato del dominio, esegui questo comando:

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

Per ulteriori informazioni sullo stato dei certificati, consulta Risoluzione dei problemi relativi ai certificati SSL.

Testa il sito web

Una volta attivo il certificato SSL, verifica che i contenuti vengano pubblicati dal bucket andando a https://www.example.com/test.html, dove test.html è un oggetto archiviato nel bucket che stai utilizzando come backend. Se imposti la proprietà MainPageSuffix, https://www.example.com passa a index.html.

Esegui la pulizia

Al termine del tutorial, puoi eseguire la pulizia delle risorse che hai creato in modo che smettano di utilizzare la quota e smettano di essere addebitati. Le sezioni seguenti descrivono come eliminare o disattivare queste risorse.

Elimina il progetto

Il modo più semplice per eliminare la fatturazione è eliminare il progetto che hai creato per il tutorial.

Per eliminare il progetto:

  1. Nella console Google Cloud, vai alla pagina Gestisci risorse.

    Vai a Gestisci risorse

  2. Nell'elenco dei progetti, seleziona il progetto che vuoi eliminare, quindi fai clic su Elimina.
  3. Nella finestra di dialogo, digita l'ID del progetto e fai clic su Chiudi per eliminare il progetto.

Elimina il bilanciatore del carico e il bucket

Se non vuoi eliminare l'intero progetto, elimina il bilanciatore del carico e il bucket che hai creato per il tutorial:

  1. Vai alla pagina Bilanciamento del carico nella console Google Cloud.
    Vai a Bilanciamento del carico
  2. Seleziona la casella di controllo accanto a example-lb.
  3. Fai clic su Elimina.
  4. (Facoltativo) Seleziona la casella di controllo accanto alle risorse che vuoi eliminare insieme al bilanciatore del carico, ad esempio il bucket my-static-assets o il certificato SSL example-ssl.
  5. Fai clic su Elimina bilanciatore del carico o Elimina il bilanciatore del carico e le risorse selezionate.

Rilascia un indirizzo IP riservato

Per eliminare l'indirizzo IP riservato che hai utilizzato per il tutorial:

  1. Nella console Google Cloud, vai alla pagina Indirizzi IP esterni.

    Vai a Indirizzi IP esterni

  2. Seleziona le caselle di controllo accanto a example-ip.

  3. Fai clic su Rilascia indirizzo statico.

  4. Nella finestra di conferma, fai clic su Delete (Elimina).

Passaggi successivi

Provalo

Se non conosci Google Cloud, crea un account per valutare le prestazioni di Cloud Storage in scenari reali. I nuovi clienti ricevono anche 300 $ di crediti gratuiti per l'esecuzione, il test e il deployment dei carichi di lavoro.

Prova Cloud Storage gratis