关于在Google Cloud Run中实现WWW域名到非WWW域名重定向的技术咨询
Hey Adam, totally get where you’re coming from—Cloud Run’s architecture works a bit differently from Apache/Nginx, so those familiar server config files don’t exist here. Let’s break down the main ways to set up that www-to-non-www redirect:
1. Handle Redirects Directly in Your Application Code
Since Cloud Run runs your containerized app, the most straightforward approach is to add redirect logic right in your code. This works for any tech stack and is the easiest method if you don’t have a load balancer in front.
Here are quick examples for common frameworks:
Python (Flask)
from flask import Flask, redirect, request app = Flask(__name__) @app.before_request def redirect_www_traffic(): # Strip port number if present host = request.host.split(':')[0] if host.startswith('www.'): non_www_host = host[4:] # Preserve scheme (http/https) and request path return redirect(f"{request.scheme}://{non_www_host}{request.path}", code=301) # Your existing app routes go here
Node.js (Express)
const express = require('express'); const app = express(); app.use((req, res, next) => { const host = req.hostname; if (host.startsWith('www.')) { const nonWwwHost = host.slice(4); // 301 = permanent redirect (optimal for SEO and browser caching) return res.redirect(301, `${req.protocol}://${nonWwwHost}${req.originalUrl}`); } next(); }); // Rest of your Express app setup
2. Use Google Cloud Load Balancer (If You’re Using One)
If your Cloud Run service is behind a Google Cloud Load Balancer (common for production setups), you can configure the redirect directly at the LB level without touching your app code:
- Head to the URL Maps section in the Google Cloud Console
- Create a new rule that matches requests where the host is
www.example.com - Set the action to Redirect, with the target URL configured as
https://example.com$request_path - Select 301 Permanent Redirect to ensure search engines update indexes and browsers cache the rule
Key Notes
- Make sure both
www.example.comandexample.comare properly set up as custom domains for your Cloud Run service, with valid SSL certificates (Google provides free auto-renewing certs for Cloud Run custom domains) - Cloud Run doesn’t support server-level config files like
.htaccessornginx.conf—all request routing/redirect logic lives either in your app code or in upstream services like load balancers
内容的提问来源于stack exchange,提问作者user1845678

