部署環境:
CentOS release 6.7 (Final)
Python 3.5.3
Django 1.11.2
開發環境靜態資源沒有出過什么問題,一直健康良好的可訪問,可在部署到Linux生產環境后出現了訪問不到的404問題。
相對比,官方的指導還不如網上前輩總結的精辟到位。
我的 settings.py 相關配置文件如下:
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.static',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
# 設置靜態文件目錄
STATIC_PATH = os.path.join(os.path.dirname(__file__), 'static')
# 生產環境靜態資源目錄,執行 manage.py collectstatic 后靜態文件存放的路徑
STATIC_ROOT = os.path.join(BASE_DIR, 'release', 'static')
# 生產環境 執行 manage.py collectstatic 后搜索配置的文件列表,存儲至STATIC_ROOT目錄下
# 可以用來存儲公用資源,如: JQuery, bootstrap等
STATICFILES_DIRS = (
# os.path.join(os.path.dirname(__file__), '../static/').replace('\\', '/'),
)
# 配置項用來控制文件被聚集起來的方式。
# 默認值是 django.contrib.staticfiles.storage.StaticFilesStorage ,表示將文件集合在 STATIC_ROOT 配置項指定的文件夾中。
# AppDirectoriesFinder 用來在每個app中的 static 文件搜索靜態文件,如: $app_name/static/ 。
# FileSystemFinder 用來搜索在 STATICFILES_DIRS 配置項中指定的文件夾列表中尋找靜態文件。
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
配置完后在project目錄下執行manage.py collectstatic
,會將靜態資源導入/release/static目錄下。
用uwsgi啟動服務至后臺:nohup uwsgi --http :8000 -p 4 --modul horoscope_web.wsgi &
測試:通過http://***.com/static/images/grain.png
即可訪問到images下的圖片,靜態資源css, js也可以正常訪問。
但是admin后臺的靜態資源還是加載失敗,解決后補帖!
參考: