我有一个静态网站和一个 Django 应用程序后端,使用 gunicorn 在服务器的 8000 端口上运行。
我将静态网站的 CSS 文件收集到 /mywebsite-deployment/staticDir/homepage/css/static_website.css 中,并将 Django 模板的 CSS 收集到 /mywebsite-deployment/staticDir/dashboard/css/dashboard.css 中;
我能够使用 mywebsite.com 和www.mywebsite.com以及 CSS 访问静态网站,并使用 app.mywebsite.com 访问 Django 后端,但其 CSS 无法加载。
我尝试访问的模板如下所示:
{% load static %}
<html>
<head>
<link href={% static '/dashboard/css/dashboard.css' %} rel="stylesheet" type="text/css" media="all" />
</head>
我的 Django 应用程序 settings.py 如下所示:
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'staticFiles'),
]
STATIC_ROOT = '/mywebsite-deployment/staticDir/'
STATIC_URL = 'static/'
这是我的 nginx 配置:
ssl_certificate /etc/letsencrypt/live/mywebsite.co/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/mywebsite.co/privkey.pem; # managed by Certbot
root /mywebsite-deployment/staticDir/;
index /homepage/index.html;
error_page 404 500 502 503 504 /error.html;
proxy_intercept_errors on; # If proxy errors, let nginx process it
# error_log /var/log/nginx/error.log info;
server {
# If host isn't a mywebsite host, close the connection to prevent host spoofing
server_name _;
listen 80 default_server;
listen 443 ssl default_server;
return 444;
}
# Redirect HTTP requests to HTTPS
server {
server_name mywebsite.co www.mywebsite.co app.mywebsite.co;
listen 80;
return 301 https://$host$uri; # managed by Certbot
}
# Handle HTTPS static webserver requests
server {
server_name mywebsite.co www.mywebsite.co;
listen 443 ssl; # managed by Certbot
}
# Proxy HTTPS app requests to backend gunicorn service
server {
server_name app.mywebsite.co;
listen 443 ssl; # managed by Certbot
location / { # Catch all - Match everything else not matched in any above location blocks within this server block
proxy_redirect off; # Stop redirects from proxy
proxy_connect_timeout 3; # Abort if service is unreachable
proxy_read_timeout 3; # Abort if the service is unresponsive
include proxy_params;
proxy_pass http://localhost:8000;
}
# If Gunicorn Django proxy app throws an error (like 404), nginx will handle it and show custom error page
location /error.html {
internal;
}
}
当我在浏览器中检查模板 HTML 时,我看到它尝试加载的 URL 是: https://app.mywebsite.co/static/dashboard/css/dashboard.css,但它没有加载。
我可以按如下方式访问主页 CSS:https://www.mywebsite.co/homepage/css/static_website.css
按如下方式访问仪表板 CSS:
https://www.mywebsite.co/dashboard/css/dashboard.css
如何在仪表板中使用正确的路径查看 CSS?我感觉这是 Nginx 配置问题,但我是 Nginx 新手,不知道如何解决。请帮忙。