google-cloud-platformgcp-load-balancer

GCP Load balancer - prefix domain


I have a task to provide reliable solution to redirect domain, potingin to external IP to domain with prefix.

Currently I have a VM with nginx doing:

#redirect to www
server {
    listen [::]:80 reuseport default_server;
    listen 0.0.0.0:80 reuseport default_server;
    return 301 https://www.$host$request_uri;
}

I think I have found only that I can put redirect for each host, one by one...

Is there any way to do it serverless as template - add www. prefix to each querying host?


Solution

  • actually I have solved it on my own. I have create a simple App Engine service that performs simple redirect:

    from flask import Flask, request, redirect
    
    app = Flask(__name__)
    
    @app.route("/", defaults={"path": ""})
    @app.route("/<string:path>")
    @app.route("/<path:path>")
    def catch_all(path):
        host = request.headers.get("host")
        new_host = "www." + host
        new_url = request.url.replace(host, new_host, 1)
        return redirect(new_url, code=301)
    
    if __name__ == "__main__":
        app.run()
    

    Apart from that, there is need for a forwarding setup from global IP to App Enginge instance. This can be done in few ways thus leving link to docs: https://cloud.google.com/load-balancing/docs/https/setting-up-https-serverless