A solution where you don't need to modify your main application and which also works with static files is to create a service which runs on www. For that create the following files:
www.yaml
:
runtime: python27
api_version: 1
threadsafe: yes
service: www
handlers:
- url: /.*
script: redirectwww.app
redirectwww.py
:
import webapp2
class RedirectWWW(webapp2.RequestHandler):
def get(self):
self.redirect('https://example.com' + self.request.path)
app = webapp2.WSGIApplication([
('.*', RedirectWWW),
])
dipatch.yaml
:
dispatch:
- url: "www.example.com/*"
service: www
Then deploy with gcloud app deploy www.yaml dispatch.yaml
.