Google Cloud Storage:如何为WordPress网站限制文件仅特定域名可访问
Great question – yes, you absolutely can lock down your GCS bucket so only requests coming from your WordPress domain can access the files. Let’s break down the exact steps to make this happen:
1. Enforce Referer Header Restrictions at the Bucket Level
This is the core of your access control setup. GCS lets you create bucket policies that check the Referer header of incoming requests, allowing only those from your domain.
- Head to the Google Cloud Console, find your target Cloud Storage bucket.
- Navigate to the Permissions tab, then click Add condition when editing existing public permissions or creating new ones.
- Build your condition with these settings:
- Condition type:
Resource - Operator:
matches regex - Field:
request.headers.referer - Value:
^https?://yourdomain\.com(/.*)?$(swapyourdomain.comfor your actual site; add(www\.)?inside the regex if you need to include your www subdomain, like^https?://(www\.)?yourdomain\.com(/.*)?$)
- Condition type:
- Attach this condition to any permissions that grant file access – now only requests with a valid Referer from your domain will be allowed.
2. Configure CORS for Browser-Level Protection
Cross-Origin Resource Sharing (CORS) settings ensure browsers block unauthorized cross-origin requests to your GCS assets automatically.
- Create a
cors.jsonfile with this content (update the domain to match yours):[ { "origin": ["https://yourdomain.com", "http://yourdomain.com"], "method": ["GET", "HEAD"], "responseHeader": ["Content-Type"], "maxAgeSeconds": 3600 } ] - Apply this config to your bucket using the
gsutilcommand:
(If you don’t havegsutil cors set cors.json gs://your-bucket-namegsutilset up, you can also edit CORS settings directly in the Cloud Console under your bucket’s Permissions > CORS tab.)
3. Tweak WordPress to Ensure Proper Referer Headers
Most browsers send the Referer header automatically, but a few tweaks will avoid gaps:
- If you’re using a CDN with your WordPress site, double-check that it’s configured to pass through the original Referer header to GCS.
- Avoid using
target="_blank"withoutrel="noopener noreferrer"on links leading to pages with your GCS assets – some browsers strip the Referer whennoreferreris added.
4. Optional: Use Signed URLs for Extra Security
For stricter control (like time-limited access or user-specific permissions), you can implement GCS Signed URLs in your WordPress setup:
- Write a custom WordPress function that generates signed URLs for your GCS files instead of using public links.
- Signed URLs are valid only for a set timeframe and specific conditions, so even if someone shares the link, it won’t work outside those parameters.
Note: Keep in mind that Referer headers can be spoofed in non-browser environments, but for standard web traffic from your WordPress users, this setup provides reliable protection.
内容的提问来源于stack exchange,提问作者alberto montalesi

