Search code examples
pythongoogle-app-enginewebapp2

How to do SEO Url changes and Redirects for google AppEngine Webapp2 Urls?


I am moving my company website to google app engine, Its mostly static content with small sections like dates to be generated using python. I have setup everything correctly and its working fine on app engine. Now I want to make few SEO related URL changes.

This is the line of code by which the website is served now .

app = webapp2.WSGIApplication([
    ('/', IndexPage),
    ('/discover', DiscoverPage),
    ('/about', AboutPage),
    ('/help', HelpPage),
    ('/terms-and-privacy', TermsPage)
], debug=True)

with classes like this defined for each page.

class DiscoverPage(webapp2.RequestHandler):
    def get(self):
        template_values = {
            'bodyclass': 'discover',
        }
        template = JINJA_ENVIRONMENT.get_template('discover.html')
        self.response.write(template.render(template_values))

Now the things I want to achieve are :

  • when site being accessed from www.domain.com , I would like to redirect it to domain.com .

I have added both www and non www mappings at the app engine developer console, the site is currently accessible from both www and non www urls.but I only want non www version

  • When there is a trailing slash to the urls, strip it and send to version without trailing slash.

Right now domain.com/discover works fine but domain.com/discover/ ends up in 404 .

I haven't got much experience with python webapps and my background is mainly apache/nginx servers and php . Does AppEngine got anything like htaccess rules or nginx rewrites ?


Solution

  • You could first catch ALL requests to the "www" subdomain:

    from webapp2_extras.routes import DomainRoute
    
    app = webapp2.WSGIApplication([
    
        DomainRoute('www.domain.com', [
                webapp2.Route(r'/<:.*>', handler=RedirectWWW),
        ]),
    
        ('/', IndexPage),
        ('/discover', DiscoverPage),
        ('/about', AboutPage),
        ('/help', HelpPage),
        ('/terms-and-privacy', TermsPage)
    ], debug=True)
    

    with a handler that replaces the www part with the naked domain:

    class RedirectWWW(webapp2.RequestHandler):
        def get(self, *args, **kwargs):
            url = self.request.url.replace(self.request.host, 'domain.com')
            return self.redirect(url, permanent=True)
    
        def post(self, *args, **kwargs):
            return self.get()
    

    Regarding the second issue, you could read about the strict_slash parameter here: https://webapp-improved.appspot.com/api/webapp2_extras/routes.html