Search code examples
flasksubdomain

Flask with subdomain breaks links to static resources


I added subdomains support:

  1. C:\Windows\System32\drivers\etc\hosts:
    127.0.0.1       subdomain.test.com
  1. Flask config:
    SERVER_NAME = 'test.com:5005'
  1. Blueprint:
@app_blueprint.route('/', methods=['GET'], subdomain='<subdomain_name>') 
def index(subdomain_name):
    return redirect(url_for('app.index'))

It successfully finds the route but when it loads the template app.html into the browser it can't resolve the static resource:

Instead of

<script src="http://subdomain.test.com:5005/static/dist/app.bundle.js"></script> 

it resolves as

<script src="http://test.com:5005/static/dist/app.bundle.js"></script> 

and can't find it.

What am I missing?

Update. I updated the hosts file according to Sean's answer. But now Flask can't find the endpoint "app.index" that I'm redirecting to.

I specified it as:

@app_blueprint.route('/app', methods=['GET'], subdomain='<subdomain_name>')
@app_blueprint.route('/app/<path:path>', methods=['GET'], subdomain='<subdomain_name>')
def index(path = None, subdomain_name=None):
    return render_template('app.html', subdomain_name=subdomain_name)

This endpoind can be hit if I use /app in browser directly but redirection doesn't work and other things can'be found either.


Solution

  • You also need to add test.com to your /etc/hosts alias:

    127.0.0.1       subdomain.test.com  test.com
    

    You told Flask that you're mounted at test.com and so it mounted the /static routes there ... but your network layer doesn't know where test.com is because you haven't told it where it lives.