אירוח אתרים סטטיים

בדף הזה מוסבר איך להגדיר קטגוריה של Cloud Storage לאירוח אתר סטטי בשביל דומיין שנמצא בבעלותכם. דפי אינטרנט סטטיים יכולים להכיל טכנולוגיות בצד הלקוח, כמו HTML, CSS ו-JavaScript. הם לא יכולים להכיל תוכן דינמי, כמו סקריפטים בצד השרת, למשל PHP.

סקירה כללית

מכיוון ש-Cloud Storage לא תומך בעצמו בדומיינים מותאמים אישית עם HTTPS, המדריך הזה משתמש ב-Cloud Storage עם מאזן עומסים חיצוני של אפליקציות (ALB) כדי להציג תוכן מדומיין מותאם אישית ב-HTTPS. לדרכים נוספות להצגת תוכן מדומיין מותאם אישית באמצעות HTTPS, אפשר לעיין בפתרון בעיות בהצגת HTTPS. אפשר גם להשתמש ב-Cloud Storage כדי להציג תוכן של דומיין מותאם אישית באמצעות HTTP, שאינו דורש מאזן עומסים.

אפשר למצוא דוגמאות וטיפים בנושא דפי אינטרנט סטטיים, כולל הנחיות לאירוח נכסים סטטיים באתר דינמי במאמר דף אתר סטטי.

בדף הזה מוסבר איך לבצע את השלבים הבאים:

  • להעלות את קובצי האתר ולשתף אותם.

  • להגדיר את מאזן עומסים ואישור SSL.

  • לחבר את מאזן העומסים לקטגוריה.

  • להפנות את הדומיין למאזן העומסים באמצעות רשומת A.

  • לבדוק את האתר.

תמחור

ההוראות בדף הזה מתייחסות לרכיבים הבאים שלGoogle Cloud, והשימוש בהם כרוך בתשלום:

בטיפ למעקב אחרי החיובים מפורט אילו חיובים עשויים לחול באירוח של אתר סטטי.

מגבלות

אפשר לארח אתר סטטי באמצעות קטגוריה שהאובייקטים שלה ניתנים לקריאה על ידי הציבור. אי אפשר לארח אתר סטטי באמצעות קטגוריה שמופעלת בה מניעת גישה ציבורית. כדי לארח אתר סטטי באמצעות Cloud Storage, אפשר להשתמש באחת מהשיטות הבאות:

  • יוצרים קטגוריה חדשה שהנתונים שלה נגישים באופן ציבורי. במהלך יצירת הקטגוריה, מבטלים את הסימון בתיבה Enforce public access prevention on this bucket. אחרי שיוצרים את הקטגוריה, מקצים את התפקיד 'צפייה באובייקט אחסון' לחשבון המשתמש allUsers. מידע נוסף זמין במאמר בנושא יצירת קטגוריה.

  • הגדרת הנתונים בקטגוריה קיימת כציבוריים. מידע נוסף מופיע במאמר בנושא שיתוף קבצים.

לפני שמתחילים

  1. נכנסים לחשבון Google Cloud . אם אתם משתמשים חדשים ב- Google Cloud, צרו חשבון כדי שתוכלו להעריך את הביצועים של המוצרים שלנו בתרחישים מהעולם האמיתי. לקוחות חדשים מקבלים בחינם גם קרדיט בשווי 300$ להרצה, לבדיקה ולפריסה של עומסי העבודה.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

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

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  5. Verify that billing is enabled for your Google Cloud project.

  6. מפעילים את Compute Engine API בפרויקט.
  7. מוודאים את קיומם של התפקידים הבאים של ניהול זהויות והרשאות גישה (IAM): אדמין אחסון ואדמין רשת Compute.
  8. אתם צריכים דומיין שאתם מנהלים או הבעלים שלו. אם אין לכם דומיין קיים, יש שירותים רבים שבאמצעותם אפשר לרשום דומיין חדש, כמו Cloud Domains.

    המדריך זה משתמש בדומיין example.com.

  9. אתם צריכים מספר קובצי אתר שאתם רוצים להציג. המדריך הזה עובד בצורה הטובה ביותר אם יש לכם לפחות דף אינדקס (index.html) ודף 404 (404.html).
  10. יש לכם קטגוריה ב-Cloud Storage לאחסון הקבצים שאתם רוצים להציג. אם אין לכם קטגוריה כרגע, צרו קטגוריה.
  11. (אופציונלי) אם רוצים שהשם של הקטגוריה של Cloud Storage יהיה זהה לזה של הדומיין, צריך לבצע אימות שאתם הבעלים או המנהלים של הדומיין שבו תשתמשו מוודאים שהאימות מתבצע בדומיין ברמה עליונה, כמו example.com, ולא בתת-דומיין, כמו www.example.com. אם רכשתם את הדומיין דרך Cloud Domains, האימות מתבצע באופן אוטומטי.

העלאת הקבצים של האתר שלכם

הוספה לאתר של הקבצים שרוצים להציג בקטגוריה:

המסוף

  1. במסוף Google Cloud , נכנסים לדף Buckets של Cloud Storage.

    כניסה לדף Buckets

  2. ברשימת הקטגוריות, לוחצים על שם הקטגוריה שיצרתם.

    הדף Bucket details נפתח והכרטיסייה Objects מסומנת.

  3. לוחצים על הלחצן Upload files.

  4. בתיבת הדו-שיח של הקובץ, מחפשים את הקובץ הרצוי ובוחרים אותו.

בסיום ההעלאה שם הקובץ צריך להופיע בקטגוריה יחד עם פרטי הקובץ.

במאמר פתרון בעיות מוסבר איך מקבלים מידע מפורט על שגיאות בנושא פעולות ב-Cloud Storage שנכשלו ב Google Cloud מסוף.

שורת הפקודה

כדי להעתיק קבצים לקטגוריה, משתמשים בפקודה gcloud storage cp. לדוגמה, כדי להעתיק את הקובץ index.html מהמיקום הנוכחי שלו Desktop לקטגוריה my-static-assets:

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

אם הפעולה בוצעה ללא שגיאות, התשובה תיראה כמו בדוגמה הבאה:

Completed files 1/1 | 164.3kiB/164.3kiB

ספריות לקוח

C++

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage C++ API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

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#

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage C# API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.


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

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Go API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

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

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Java API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

הדוגמה הבאה מעלה אובייקט ספציפי:


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

בדוגמה הבאה מועלים כמה אובייקטים בו-זמנית:

import com.google.cloud.storage.transfermanager.ParallelUploadConfig;
import com.google.cloud.storage.transfermanager.TransferManager;
import com.google.cloud.storage.transfermanager.TransferManagerConfig;
import com.google.cloud.storage.transfermanager.UploadResult;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;

class UploadMany {

  public static void uploadManyFiles(String bucketName, List<Path> files) throws IOException {
    TransferManager transferManager = TransferManagerConfig.newBuilder().build().getService();
    ParallelUploadConfig parallelUploadConfig =
        ParallelUploadConfig.newBuilder().setBucketName(bucketName).build();
    List<UploadResult> results =
        transferManager.uploadFiles(files, parallelUploadConfig).getUploadResults();
    for (UploadResult result : results) {
      System.out.println(
          "Upload for "
              + result.getInput().getName()
              + " completed with status "
              + result.getStatus());
    }
  }
}

בדוגמה הבאה כל האובייקטים עם אותה הקידומת מועלים בו-זמנית:

import com.google.cloud.storage.transfermanager.ParallelUploadConfig;
import com.google.cloud.storage.transfermanager.TransferManager;
import com.google.cloud.storage.transfermanager.TransferManagerConfig;
import com.google.cloud.storage.transfermanager.UploadResult;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

class UploadDirectory {

  public static void uploadDirectoryContents(String bucketName, Path sourceDirectory)
      throws IOException {
    TransferManager transferManager = TransferManagerConfig.newBuilder().build().getService();
    ParallelUploadConfig parallelUploadConfig =
        ParallelUploadConfig.newBuilder().setBucketName(bucketName).build();

    // Create a list to store the file paths
    List<Path> filePaths = new ArrayList<>();
    // Get all files in the directory
    // try-with-resource to ensure pathStream is closed
    try (Stream<Path> pathStream = Files.walk(sourceDirectory)) {
      pathStream.filter(Files::isRegularFile).forEach(filePaths::add);
    }
    List<UploadResult> results =
        transferManager.uploadFiles(filePaths, parallelUploadConfig).getUploadResults();
    for (UploadResult result : results) {
      System.out.println(
          "Upload for "
              + result.getInput().getName()
              + " completed with status "
              + result.getStatus());
    }
  }
}

Node.js

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Node.js API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

הדוגמה הבאה מעלה אובייקט ספציפי:

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

בדוגמה הבאה מועלים כמה אובייקטים בו-זמנית:

/**
 * 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 upload
// const firstFilePath = 'your-first-file-name';

// The ID of the second GCS file to upload
// 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);

בדוגמה הבאה כל האובייקטים עם אותה הקידומת מועלים בו-זמנית:

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

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage PHP API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

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

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Python API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

הדוגמה הבאה מעלה אובייקט ספציפי:

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

בדוגמה הבאה מועלים כמה אובייקטים בו-זמנית:

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

בדוגמה הבאה כל האובייקטים עם אותה הקידומת מועלים בו-זמנית:

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

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Ruby API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

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

Rust

use google_cloud_storage::client::Storage;

pub async fn sample(
    client: &Storage,
    bucket: &str,
    object: &str,
    file_path: &str,
) -> Result<(), anyhow::Error> {
    let payload = tokio::fs::File::open(file_path).await?;
    let _result = client
        .write_object(format!("projects/_/buckets/{bucket}"), object, payload)
        .send_unbuffered()
        .await?;

    println!("Uploaded {file_path} to {object} in bucket {bucket}.");
    Ok(())
}

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. התקנה והפעלה של ה-CLI של gcloud, שמאפשרות ליצור אסימון גישה לכותרת Authorization.

  2. משתמשים ב- cURL כדי לשלוח קריאה ל-API בפורמט JSON באמצעות בקשת אובייקט POST. עם הקובץ index.html שהועלה לקטגוריה 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. התקנה והפעלה של ה-CLI של gcloud, שמאפשרות ליצור אסימון גישה לכותרת Authorization.

  2. משתמשים ב- cURL כדי לשלוח קריאה ל-API בפורמט XML באמצעות בקשת אובייקט PUT: עם הקובץ index.html שהועלה לקטגוריה 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"

שיתוף הקבצים שלכם

כדי שכל האובייקטים שבקטגוריה יהיו קריאים לכולם באינטרנט הציבורי:

המסוף

  1. במסוף Google Cloud , נכנסים לדף Buckets של Cloud Storage.

    כניסה לדף Buckets

  2. ברשימת הקטגוריות, לוחצים על השם של הקטגוריה שרוצים להגדיר כציבורית.

  3. לוחצים על הכרטיסייה הרשאות בחלק העליון של הדף.

  4. אם בחלונית Public access כתוב Not public, לוחצים על הלחצן Remove public access Prevention ואז לוחצים על Confirm בתיבת הדו-שיח שמופיעה.

  5. לוחצים על הלחצן Grant access.

    מופיעה תיבת הדו-שיח Add principals.

  6. בשדה New principals, מזינים allUsers.

  7. בתפריט הנפתח Select a role, בוחרים את תפריט המשנה Cloud Storage, ולוחצים על האפשרות Storage Object Viewer.

  8. לוחצים על Save.

  9. לוחצים על Allow Public Access.

אחרי השיתוף באופן ציבורי, בעמודה public access מופיע סמל קישור לכל אובייקט. אפשר ללחוץ על הסמל הזה כדי לקבל את כתובת ה-URL של האובייקט.

במאמר פתרון בעיות מוסבר איך מקבלים מידע מפורט על שגיאות בנושא פעולות ב-Cloud Storage שנכשלו ב Google Cloud מסוף.

שורת הפקודה

משתמשים בפקודה buckets add-iam-policy-binding:

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

ספריות לקוח

C++

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage C++ API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

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#

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage C# API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.


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

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Go API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

import (
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/iam"
	"cloud.google.com/go/iam/apiv1/iampb"
	"cloud.google.com/go/storage"
)

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

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Java API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

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

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Node.js API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

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

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage PHP API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

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

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Python API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

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

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Ruby API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

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

Rust

use google_cloud_iam_v1::model::Binding;
use google_cloud_storage::client::StorageControl;

pub async fn sample(client: &StorageControl, bucket_id: &str) -> anyhow::Result<()> {
    let mut policy = client
        .get_iam_policy()
        .set_resource(format!("projects/_/buckets/{bucket_id}"))
        .send()
        .await?;
    policy.bindings.push(
        Binding::new()
            .set_role("roles/storage.objectViewer")
            .set_members(vec!["allUsers".to_string()]),
    );
    let updated_policy = client
        .set_iam_policy()
        .set_resource(format!("projects/_/buckets/{bucket_id}"))
        .set_policy(policy)
        .send()
        .await?;
    println!(
        "Successfully set public IAM policy for bucket {}",
        bucket_id
    );
    println!("The updated policy is: {:?}", updated_policy);
    Ok(())
}

Terraform

# Make bucket public by granting allUsers storage.objectViewer access
resource "google_storage_bucket_iam_member" "public_rule" {
  bucket = google_storage_bucket.static_website.name
  role   = "roles/storage.objectViewer"
  member = "allUsers"
}

ממשקי API ל-REST

‫API בפורמט JSON

  1. התקנה והפעלה של ה-CLI של gcloud, שמאפשרות ליצור אסימון גישה לכותרת Authorization.

  2. יוצרים קובץ JSON שמכיל את הפרטים הבאים:

    {
      "bindings":[
        {
          "role": "roles/storage.objectViewer",
          "members":["allUsers"]
        }
      ]
    }
  3. משתמשים ב- cURL כדי לשלוח קריאה ל-API בפורמט JSON באמצעות בקשה של קטגוריית PUT:

    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"

    כאשר:

    • JSON_FILE_NAME הוא הנתיב לקובץ JSON שיצרתם בשלב 2.
    • BUCKET_NAME הוא שם הקטגוריה שרוצים להגדיר את האובייקטים שלה כציבוריים. לדוגמה, my-static-assets.

‫API בפורמט XML

ב-API בפורמט XML אין תמיכה בהגדרת כל האובייקטים בקטגוריה כקריאים באופן ציבורי. במקום זאת, השתמשו במסוף Google Cloud או ב-gcloud storage, או הגדירו רשימות ACL לכל אובייקט בנפרד. שימו לב: כדי להגדיר רשימות ACL לכל אובייקט בנפרד, צריך לשנות את מצב בקרת גישה של הקטגוריה ל-Fine-grained.

אם רוצים, אפשר גם להגדיר חלקים מהקטגוריה כנגישים באופן ציבורי.

המבקרים יקבלו קוד תגובה http 403 כשהם מבקשים את כתובת ה-URL של קובץ שאינו ציבורי או לא קיים. בסעיף הבא מוסבר איך להוסיף דף שגיאה שמשתמש בקוד התגובה http 404.

מומלץ: הקצאת דפים מיוחדים

אפשר להקצות סיומת של דף אינדקס ודף שגיאה מותאם אישית, שמוכרים בשם דפים מיוחדים. לא חובה להקצות אף אחד מהם, אבל במקרה שלא מקצים סיומת של דף אינדקס ומעלים את דף האינדקס המתאים, למשתמשים שנכנסים לאתר שברמה העליונה יוצג עץ של מסמכי XML שמכיל רשימה של האובייקטים הציבוריים בקטגוריה.

מידע נוסף על ההתנהגות של דפים מיוחדים זמין בדפים מיוחדים.

המסוף

  1. במסוף Google Cloud , נכנסים לדף Buckets של Cloud Storage.

    כניסה לדף Buckets

  2. מוצאים ברשימת הקטגוריות את הקטגוריה שיצרתם.

  3. לוחצים על התפריט Bucket overflow () שמשויך לקטגוריה ובוחרים באפשרות Edit website configuration.

  4. בתיבת הדו-שיח של הגדרת האתר, מציינים את הדף הראשי ואת דף השגיאה.

  5. לוחצים על Save.

במאמר פתרון בעיות מוסבר איך מקבלים מידע מפורט על שגיאות בנושא פעולות ב-Cloud Storage שנכשלו ב Google Cloud מסוף.

שורת הפקודה

השתמש בפקודה buckets update עם הדגלים --web-main-page-suffix ו---web-error-page.

בדוגמה הבאה, MainPageSuffix מוגדר להיות index.html ו-NotFoundPage מוגדר להיות 404.html:

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

אם הפעולה הצליחה, הפקודה תחזיר:

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

ספריות לקוח

C++

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage C++ API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

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#

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage C# API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.


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

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Go API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

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

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Java API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

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

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Node.js API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

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

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage PHP API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

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

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Python API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

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

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Ruby API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

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

Rust

use google_cloud_storage::client::StorageControl;
use google_cloud_storage::model::bucket::Website;
use google_cloud_wkt::FieldMask;

pub async fn sample(
    client: &StorageControl,
    bucket_id: &str,
    main_page_suffix: &str,
    not_found_page: &str,
) -> anyhow::Result<()> {
    let bucket = client
        .get_bucket()
        .set_name(format!("projects/_/buckets/{bucket_id}"))
        .send()
        .await?;
    let metageneration = bucket.metageneration;
    let website = Website::new()
        .set_main_page_suffix(main_page_suffix)
        .set_not_found_page(not_found_page);
    let bucket = client
        .update_bucket()
        .set_bucket(bucket.set_website(website))
        .set_if_metageneration_match(metageneration)
        .set_update_mask(FieldMask::default().set_paths(["website"]))
        .send()
        .await?;
    println!(
        "Website configuration for bucket {} defined as: {:?}",
        bucket_id, bucket.website
    );
    Ok(())
}

ממשקי API ל-REST

‫API בפורמט JSON

  1. התקנה והפעלה של ה-CLI של gcloud, שמאפשרות ליצור אסימון גישה לכותרת Authorization.

  2. יוצרים קובץ JSON שמגדיר את המאפיינים mainPageSuffix ו-notFoundPage באובייקט website לדפים הרצויים.

    בדוגמה הבאה, mainPageSuffix מוגדר להיות index.html ו-notFoundPage מוגדר להיות 404.html:

    {
      "website":{
        "mainPageSuffix": "index.html",
        "notFoundPage": "404.html"
      }
    }
  3. משתמשים ב- cURL כדי לשלוח קריאה ל-API בפורמט JSON באמצעות בקשת קטגוריה PATCH. בקטגוריה 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. התקנה והפעלה של ה-CLI של gcloud, שמאפשרות ליצור אסימון גישה לכותרת Authorization.

  2. יוצרים קובץ XML שמגדיר את הרכיבים MainPageSuffix ו-NotFoundPage ברכיב WebsiteConfiguration לדפים הרצויים.

    בדוגמה הבאה, MainPageSuffix מוגדר להיות index.html ו-NotFoundPage מוגדר להיות 404.html:

    <WebsiteConfiguration>
      <MainPageSuffix>index.html</MainPageSuffix>
      <NotFoundPage>404.html</NotFoundPage>
    </WebsiteConfiguration>
  3. משתמשים ב- cURL כדי לשלוח קריאה ל-API בפורמט XML באמצעות בקשת קטגוריה PUT ופרמטר מחרוזת שאילתה websiteConfig. ל-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

הגדרת מאזן עומסים ואישור SSL

Cloud Storage לא תומך בעצמו בדומיינים מותאמים אישית עם HTTPS, לכן צריך גם להגדיר אישור SSL שמצורף למאזן עומסים של HTTPS. כדי לשרת את האתר באמצעות HTTPS. בסעיף הזה מוסבר איך להוסיף את הקטגוריה לקצה העורפי של מאזן עומסים, ואיך להוסיף אישור SSL חדש בניהול Google לממשק הקצה של מאזן העומסים.

בחירת סוג מאזן העומסים

  1. נכנסים לדף Load balancing במסוף Google Cloud .

    כניסה לדף Load balancing

  2. לוחצים על Create load balancer (יצירת מאזן עומסים).
  3. בקטע Type of load balancer, בוחרים באפשרות Application Load Balancer (HTTP/HTTPS) ולוחצים על Next.
  4. לוחצים על Configure (הגדרה).

יופיע חלון ההגדרה של מאזן העומסים.

הגדרה בסיסית

לפני שממשיכים בהגדרה, צריך להזין שם למאזן העומסים, לדוגמה example-lb.

הגדרת הקצה הקדמי

הסעיף הזה מסביר איך להגדיר את פרוטוקול HTTPS וליצור אישור SSL. אפשר גם לבחור אישור קיים או להעלות אישור SSL בניהול עצמי.

  1. לוחצים על Frontend configuration.
  2. (אופציונלי) נותנים שם לתצורת הקצה הקדמי.
  3. בשביל Protocol, בוחרים HTTPS (includes HTTP/2).
  4. בשביל IP version, בוחרים IPv4. אם מעדיפים להשתמש ב-IPv6, ראו מידע נוסף בסיום של IPv6.
  5. בשדה IP address:

    • בתפריט הנפתח, לוחצים על Create IP address.
    • בתיבת הדו-שיח Reserve a new static IP address, מזינים שם, לדוגמה example-ip ל-Name של כתובת ה-IP.
    • לוחצים על Reserve.
  6. בשביל Port, בוחרים 443.

  7. בתפריט הנפתח של השדה Certificate, בוחרים Create a new certificate. הטופס ליצור האישור יופיע בחלונית. קובעים את ההגדרות הבאות:

    • נותנים לאישור Name, לדוגמה example-ssl.
    • בשביל Create mode, בוחרים Create Google-managed certificate.
    • בשביל Domains, מזינים את שם האתר, לדוגמה www.example.com. אם רוצים להציג את התוכן דרך דומיינים נוספים, כמו דומיין הבסיסי (root) example.com, לוחצים על Enter כדי להוסיף אותם בשורות נוספות. לכל אישור יש הגבלה של 100 דומיינים.
  8. לוחצים על יצירה.

  9. (אופציונלי) אם רוצים ש- Google Cloud יגדיר באופן אוטומטי מאזן עומסים חלקי של HTTP להפניה אוטומטית של תעבורת HTTP, מסמנים את תיבת הסימון שלצד Enable HTTP to HTTPS redirect.

  10. לוחצים על סיום.

הגדרת הקצה העורפי

  1. לוחצים על Backend configuration.
  2. בתפריט הנפתח Backend services & backend buckets לוחצים על Create a backend bucket.
  3. בוחרים Backend bucket name, כמו example-bucket. השם שבוחרים יכול להיות שונה מהשם של הקטגוריה שיצרתם קודם.
  4. לוחצים על Browse, בשדה Cloud Storage bucket.
  5. בוחרים את הקטגוריה my-static-assets שיצרתם קודם ולוחצים על Select.
  6. (אופציונלי) אם רוצים להשתמש ב-Cloud CDN, מסמנים את תיבת הסימון Enable Cloud CDN ומגדירים את Cloud CDN בהתאם לצורך. שימו לב ש-Cloud CDN עשוי להיות כרוך בעלויות נוספות.
  7. לוחצים על Create.

הגדרת כללי ניתוב

כללי ניתוב הם הרכיבים של מפת כתובות ה-URL של מאזן עומסים חיצוני של אפליקציות (ALB) במדריך הזה צריך לדלג על החלק הזה של הגדרת מאזן העומסים, כי הוא מוגדר באופן אוטומטי לשימוש בקצה העורפי שהגדרתם כרגע.

בדיקת ההגדרות האישיות

  1. לוחצים על Review and finalize.
  2. בודקים את הקצה הקדמי, כללי הניתוב והקצה העורפי.
  3. לוחצים על Create.

יכול להיות שתצטרכו להמתין מספר דקות עד שמאזן העומסים ייווצר.

חיבור הדומיין למאזן העומסים

אחרי יצירת מאזן העומסים, לוחצים על השם של מאזן העומסים: example-lb. שימו לב לכתובת ה-IP שמשויכת למאזן העומסים: לדוגמה, 30.90.80.100. כדי להפנות את הדומיין למאזן העומסים, צריך ליצור רשומת A באמצעות שירות הרישום של הדומיין. אם הוספתם מספר דומיינים לאישור ה-SSL, צריך להוסיף רשומת A לכל אחד מהם, כשכולם מפנים לכתובת ה-IP של מאזן העומסים. לדוגמה, כדי ליצור רשומות A בשביל www.example.com ובשביל example.com:

NAME                  TYPE     DATA
www                   A        30.90.80.100
@                     A        30.90.80.100

מידע נוסף על חיבור הדומיין למאזן העומסים מופיע במאמר פתרון בעיות בסטטוס הדומיין.

יכול להיות שיעברו 60 עד 90 דקות עד שמערכת Google Cloud תקצה את האישור ותהפוך את האתר לזמין דרך מאזן העומסים. כדי לעקוב אחרי סטטוס האישור:

המסוף

  1. נכנסים לדף Load balancing במסוף Google Cloud .
    כניסה לדף Load balancing
  2. לוחצים על השם של מאזן העומסים: example-lb.
  3. לוחצים על השם של אישור ה-SSL המשויך למאזן העומסים: example-ssl.
  4. בשורות Status ו-Domain status מוצג סטטוס האישור. שניהם חייבים להיות פעילים כדי שהאישור יהיה תקף לאתר שלכם.

שורת הפקודה

  1. כדי לבדוק את סטטוס האישור, מריצים את הפקודה הבאה:

    gcloud compute ssl-certificates describe CERTIFICATE_NAME \
      --global \
      --format="get(name,managed.status)"
    
  2. כדי לבדוק את סטטוס הדומיין, מריצים את הפקודה הבאה:

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

מידע נוסף על סטטוס האישורים, מופיע במאמר פתרון בעיות הקשורות לאישורי SSL.

בדיקת האתר

אחרי שאישור ה-SSL פעיל, חשוב לוודא שהתוכן מוצג מהקטגוריה על -די מעבר אל https://www.example.com/test.html, כאשר test.html הוא אובייקט המאוחסן בקטגוריה שבה משתמשים כקצה העורפי. אם שמגדירים את המאפיין MainPageSuffix, https://www.example.com מועבר אל index.html.

הסרת המשאבים

כשמסיימים את המדריך, אפשר למחוק את המשאבים שיצרתם, כדי שהם יפסיקו להשתמש במכסה ולצבור חיובים. הסעיפים הבאים נסביר איך למחוק או להשבית את המשאבים האלו.

מחיקת הפרויקט

הדרך הקלה ביותר לבטל את החיוב היא למחוק את הפרויקט שיצרתם בשביל המדריך הזה.

כדי למחוק את הפרויקט:

  1. במסוף Google Cloud , נכנסים לדף Manage resources.

    כניסה לדף Manage resources

  2. ברשימת הפרויקטים, בוחרים את הפרויקט שרוצים למחוק ולוחצים על Delete.
  3. כדי למחוק את הפרויקט, כותבים את מזהה הפרויקט בתיבת הדו-שיח ולוחצים על Shut down.

מחיקת מאזן העומסים והקטגוריה

אם לא רוצים למחוק את הפרויקט כולו, צריך למחוק את מאזן העומסים ואת הקטגוריה שיצרתם בשביל המדריך הזה:

  1. נכנסים לדף Load balancing במסוף Google Cloud .
    כניסה לדף Load balancing
  2. מסמנים את תיבת הסימון ליד example-lb.
  3. לוחצים על Delete.
  4. (אופציונלי) מסמנים את התיבה ליד המשאבים שאותם רוצים למחוק יחד עם מאזן העומסים, כמו למשל הקטגוריה my-static-assets או אישור ה-SSL example-ssl.
  5. לוחצים על מחיקת מאזן העומסים או על מחיקת מאזן העומסים והמשאבים שנבחרו.

שחרור כתובת IP שמורה

כדי למחוק את כתובת ה-IP השמורה שבה השתמשתם במדריך הזה:

  1. נכנסים לדף External IP addresses במסוף Google Cloud .

    נכנסים אל External IP addresses

  2. מסמנים את תיבות הסימון ליד example-ip.

  3. לוחצים על External IP addresses.

  4. בחלון האישור לוחצים על Delete.

המאמרים הבאים

נסו בעצמכם

אנחנו ממליצים למשתמשים חדשים ב-Google Cloud ליצור חשבון כדי שיוכלו להעריך את הביצועים של Cloud Storage בתרחישים מהעולם האמיתי. לקוחות חדשים מקבלים בחינם גם קרדיט בשווי 300 $להרצה, לבדיקה ולפריסה של עומסי העבודה.

להתנסות ב-Cloud Storage בחינם