Since you mentioned that you are using gunicorn
, you need to make sure you are binding gunicorn to 0.0.0.0
. For example:
gunicorn --bind 0.0.0.0:80
Additionally, since you are using Nginx, make sure to configure your "server" config section, as described here:
server {
server_name example.com
location / {
proxy_redirect off;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Host $server_name;
...
}
listen 443 ssl;
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:
<link href="static/styles.css'" rel="stylesheet">
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 usual url_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
from fastapi import FastAPI, Request
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from typing import Any
import urllib
app = FastAPI()
def my_url_for(request: Request, name: str, **path_params: Any) -> str:
url = request.url_for(name, **path_params)
parsed = list(urllib.parse.urlparse(url))
#parsed[0] = 'https' # Change the scheme to 'https' (Optional)
parsed[1] = 'my_domain.com' # Change the domain name
return urllib.parse.urlunparse(parsed)
app.mount('/static', StaticFiles(directory='static'), name='static')
templates = Jinja2Templates(directory='templates')
templates.env.globals['my_url_for'] = my_url_for
Frontend
<link href="{{ my_url_for(request, 'static', path='/styles.css') }}" rel="stylesheet">