如何让Nginx从Django站点加载静态文件

mctunoxg  于 2023-08-03  发布在  Nginx
关注(0)|答案(1)|浏览(108)

我用nginx部署了我的django站点,但是我的静态文件比如css,js或者媒体文件没有被加载,所以我需要帮助配置它
my site where the static files are not being loaded
在Web控制台中,我收到以下错误:

16Refused to apply style from '<URL>' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

字符串
我的settings.py:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

STATIC_URL = '/static/'
STATIC_ROOT = 'deploystatic'
STATICFILES_DIRS = [BASE_DIR / 'static']

MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'

# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'


我的配置在nano /etc/nginx/sites-available/myproject

server {
    listen 80;
    server_name ecommerce.jamelaumn.com;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl;
    server_name ecommerce.jamelaumn.com;
    ssl_certificate something/fullchain.pem;
    ssl_certificate_key somethingblablabla/privkey.pem;

    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}


我的nginx.conf可能一切都有默认配置

hxzsmxv2

hxzsmxv21#

首先运行这个命令:

python manage.py collectstatic

字符串
然后像这样更新你的nginx文件:

server {
    listen 80;
    server_name ecommerce.jamelaumn.com;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl;
    server_name ecommerce.jamelaumn.com;
    ssl_certificate something/fullchain.pem;
    ssl_certificate_key somethingblablabla/privkey.pem;

    location /static/ {
        alias /path/to/your/staticfiles/;
    }

    location /media/ {
        alias /path/to/your/mediafiles/;
    }

    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}


确保将/path/to/your/staticfiles//path/to/your/mediafiles/分别替换为静态文件目录和媒体文件目录的实际路径。测试你的nginx是否正常工作:

sudo nginx -t


如果没有问题,则重新启动nginx以应用更改:

sudo service nginx restart


希望对你有帮助…

相关问题