django - 如何通过 HTTPS 提供 Django 静态文件?

标签 django static https image-scaling

访问通过 HTTPS 提供的静态文件时出现 404 错误,但静态文件通过 HTTP 工作正常。

需要明确的是,我可以通过两种方式访问​​特定页面,例如http://domain.com/pagehttps://domain.com/page但在 HTTPS 情况下,图像将无法加载。

此外,直接访问图像 http://domain.com/static/image.png有效但 https://domain.com/static/image.png返回 404。

我在 apache2 上使用 mod_wsgi 运行带有 Django 1.3 的 Ubuntu 10.04。

以下是相关文件(wsgi 和 prod.conf 以及 secure_prod.conf 和 settings.py):

django.wsgi

import os
import sys
import site

sys.stdout = sys.stderr # Allows use of print statements

PROJECT_ROOT = '/home/code/domain/src/domain-project/'
site_packages = '/home/code/domain/lib/python2.6/site-packages'

site.addsitedir(os.path.abspath(site_packages))
sys.path.insert(0, PROJECT_ROOT)
sys.path.insert(1, os.path.join(PROJECT_ROOT, "domain"))
sys.path.insert(2, site_packages)
os.environ['DJANGO_SETTINGS_MODULE'] = 'domain.settings'
os.environ['PYTHON_EGG_CACHE'] = '/home/administrator/.python-eggs'
os.environ["CELERY_LOADER"] = "django"

import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()

# Load a monitor to automatically reload apache when files change
import domain.monitor
domain.monitor.start(interval=1.0)

生产配置文件
<VirtualHost *:80>

  # Admin email, Server Name (domain name) and any aliases
  ServerAdmin d@domain.com
  ServerName domain.com
    ServerAlias *.domain.com

  DocumentRoot /home/code/domain/src/domain-project/domain
  LogLevel warn
  WSGIDaemonProcess domain-production processes=5 maximum-requests=500 threads=100
  WSGIProcessGroup domain-production
  WSGIScriptAlias / /home/code/domain/src/domain-project/apache/production.wsgi

  SetEnv PYTHON_EGG_CACHE /home/apache/.python_eggs

    Alias /admin/media /home/code/domain/lib/python2.6/site-packages/django/contrib/admin/media
    Alias /site_media /home/code/domain/src/domain-project/static
    Alias /static /home/code/domain/src/domain-project/static
    Alias /robots.txt /home/code/domain/src/domain-project/static/robots.txt
    Alias /favicon.ico /home/code/domain/src/domain-project/static/favicon.ico

  <Location /admin/media>
    SetHandler None
    Order allow,deny
    Allow from all
  </Location>

  <Location /site_media>
    SetHandler None
    Order allow,deny
    Allow from all
  </Location>

  <LocationMatch "\.(jpg|gif|png|mp4)$">
    SetHandler None
  </LocationMatch>

  <LocationMatch "^/(robots\.txt|favicon\.ico|crossdomain\.xml)$">
    SetHandler none
  </LocationMatch>

  ErrorLog /var/log/apache2/domain/production_error.log
  LogLevel info
  CustomLog /var/log/apache2/domain/production_access.log combined

</VirtualHost>

安全生产.conf
<VirtualHost *:443>

    ServerAdmin d@domain.com
    ServerName domain.com
    ServerAlias *.domain.com

    DocumentRoot /home/code/domain/src/domain-project/domain 
    LogLevel warn
    WSGIDaemonProcess domain-production processes=5 maximum-requests=500 threads=100
    WSGIProcessGroup domain_production_secure
    WSGIScriptAlias / /home/code/domain/src/domain-project/apache/production.wsgi

    SSLEngine on
    SSLOptions +StrictRequire

    <Directory />
        SSLRequireSSL
    </Directory>

    SSLProtocol -all +TLSv1 +SSLv3
    SSLCipherSuite HIGH:MEDIUM:!aNULL:+SHA1:+MD5:+HIGH:+MEDIUM

    SSLCertificateFile /home/code/domain/src/domain-project/apache/key/domain.COM.crt
    SSLCertificateKeyFile /home/code/domain/src/domain-project/apache/key/domain.com.key
    SSLCertificateChainFile /home/code/domain/src/domain-project/apache/key/Apache_Plesk_Install.txt
    SSLVerifyClient none
    SSLProxyEngine off

    <IfModule mime.c>
        AddType application/x-x509-ca-cert      .crt
        AddType application/x-pkcs7-crl         .crl
    </IfModule>


    SetEnv PYTHON_EGG_CACHE /home/apache/.python_eggs


    Alias /admin/media /home/code/domain/lib/python2.6/site-packages/django/contrib/admin/media
    Alias /site_media /home/code/domain/src/domain-project/static
    Alias /static /home/code/domain/src/domain-project/static
    Alias /robots.txt /home/code/domain/src/domain-project/static/robots.txt
    Alias /favicon.ico /home/code/domain/src/domain-project/static/favicon.ico


    <Location /admin/media>
      SetHandler None
      Order allow,deny
      Allow from all
    </Location>

    <Location /site_media>
      SetHandler None
      Order allow,deny
      Allow from all
    </Location>

    <LocationMatch "\.(jpg|gif|png|mp4)$">
      SetHandler None
    </LocationMatch>

    <LocationMatch "^/(robots\.txt|favicon\.ico|crossdomain\.xml)$">
      SetHandler none
    </LocationMatch>

    ErrorLog /var/log/apache2/domain/production_secure_error.log
    LogLevel info
    CustomLog /var/log/apache2/domain/production_secure_access.log combined

</VirtualHost>

设置.py
# Django settings for domain project.
import os

DEBUG = False
TEMPLATE_DEBUG = DEBUG 

# create a relative path to anything on the project from the PROJECT PATH
SETTINGS_PATH = os.path.dirname(os.path.abspath(__file__))
PROJECT_PATH = os.path.join(*os.path.split(SETTINGS_PATH)[:-1])
rel = lambda * args: os.path.join(PROJECT_PATH, *args)

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = rel('..', 'static')

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'

# Additional locations of static files
STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
#     'django.template.loaders.eggs.Loader',
)

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.contrib.auth.context_processors.auth',
    'django.core.context_processors.debug',
    'django.core.context_processors.i18n',
    'django.core.context_processors.request',
    'django.core.context_processors.static',
)


MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
)

ROOT_URLCONF = 'domain.urls'

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    rel('..', 'templates'),
)

DJANGO_APPS= [
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.admin',
]

THIRDPARTY_APPS = [
    'djcelery',
    'djkombu',
    #'sentry',
    #'sentry.client',
    #'south',
]

domain_APPS= []

INSTALLED_APPS = DJANGO_APPS + THIRDPARTY_APPS + domain_APPS

最佳答案

您还需要为所有静态媒体和管理文件设置别名。

目前您似乎在端口 80 和 443 上服务 django,但站点媒体仅在端口 80 上。只需将别名规则和位置部分复制到 secure_production.conf

关于django - 如何通过 HTTPS 提供 Django 静态文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6950767/

相关文章:

django - iFrame 在 Facebook Canvas 应用程序中显示为空白

python - 无法将 None 分配给 Django DateTimeField()

python - Django SQLite 在测试时试图覆盖数据库

java - 如果静态内部类也是最终的,这意味着什么?

django - 在Django-Celery中停止/清除定期任务

c++ - header 中的 private static const 成员变量与 cpp 中的 const 变量

ubuntu - 在 Ubuntu Server 12.04 上设置静态 IP 会丢失外部连接

facebook - 我们可以将 url 从 https 更改为 http 从加载在基本 url 中的 iframe 吗?

iis-7 - 查看证书时是否应该能够看到 subjectAltName 选项?

objective-c - objective c 在异步 https 请求时检查服务器证书