I have a FastAPI web application using Jinja2 templates, which is working fine on localhost
, but not in production. The problem is that is not generating URLs for JavaScript and other static
files correctly. I have deployed it on EC2 instance using gunicorn
and nginx
.
I have this line of code in my HTML file:
<script src="{{ url_for('static', path='js/login_signup.js') }}"></script>
The problem is that it is generating the URL like this:
<script src="http://127.0.0.1:8000/static/js/login_signup.js"></script>
What I want is to generate something like this:
<script src="http://my_domain.com/static/js/login_signup.js"></script>
2
Answers
Serve on
0.0.0.0
instead of127.0.0.1
. If you’re usinguvicorn
which is the default web server for FastAPI, you need to pass--host 0.0.0.0
when starting the server. For other servers, look up the equivalent flag.Since you mentioned that you are using
gunicorn
, you need to make sure you are binding gunicorn to0.0.0.0
. For example:Additionally, since you are using Nginx, make sure to configure your "server" config section, as described here:
If the above does not solve the issue for you, see other options below.
Option 1
You can use realtive paths instead, as described here and here. Example:
Option 2
You can create a custom function (i.e.,
my_url_for()
in the exmaple below), which will be used to replace the URL’s domain name (hostname)—you can omit the port number when replacing the hostname, if you are relying on the default port of HTTP (80) or HTTPS (443) protocol—and use that function inside your Jinja2 templates instead of the usualurl_for()
function. If you would also like to include query parameters in the URL, rather than just path parameters, have a look at this answer and this answer. Example:Backend
Frontend