You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django网站部署Nginx+Gunicorn后静态与媒体文件无法显示求助

Django部署后静态文件与媒体文件无法显示问题

问题概述

在VPS上部署Django网站后,网站主体功能可正常运行,但静态文件(CSS、JavaScript、图片等)和媒体文件无法在页面中加载显示。已尝试多种配置调整并重启相关服务,问题仍未解决。

当前配置信息

Nginx配置

server {
    listen 80;
    server_name domain_name;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /var/www/real_estate/static/;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/run/gunicorn.sock;
    }
}

gunicorn.service配置

[Unit]
Description=gunicorn daemon
Requires=gunicorn.socket
After=network.target

[Service]
User=shahriar
Group=www-data
WorkingDirectory=/home/shahriar/Amlak/real_estate
ExecStart=/home/shahriar/Amlak/env/bin/gunicorn \
          --access-logfile - \
          --workers 3 \
          --bind unix:/run/gunicorn.sock \
          real_estate.wsgi:application

[Install]
WantedBy=multi-user.target

settings.py配置

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/

STATIC_URL = '/var/www/real_estate/static/'
STATIC_ROOT = '/var/www/real_estate/static/assets'
STATICFILES_DIRS = [ 'static/', BASE_DIR/'static/', '/var/www/real_estate/static/'

]

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

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'


# Media Settings

MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR.joinpath('media')

已尝试的调整操作

1. 修改settings.py静态文件配置

  • 修改前:
STATIC_URL = 'static/'
STATIC_ROOT = 'assets/'
STATICFILES_DIRS = [ 'static/', BASE_DIR/'static/'
]
  • 修改后:
STATIC_URL = '/var/www/real_estate/static/'
STATIC_ROOT = '/var/www/real_estate/static/assets'
STATICFILES_DIRS = [ 'static/', BASE_DIR/'static/', '/var/www/real_estate/static/'

]

2. 调整Nginx的location规则

  • 修改前:
server {
    listen 80;
    server_name domain_name;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /var/www/real_estate/static/;
    }
    location /assets/ {
        root /var/www/real_estate/assets/;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/run/gunicorn.sock;
    }
}
  • 修改后:
server {
    listen 80;
    server_name domain_name;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /var/www/real_estate/static/;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/run/gunicorn.sock;
    }
}

内容的提问来源于stack exchange,提问作者Alin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 07:57:47