jonathanatx
jonathanatx

Reputation: 1613

Django SSL cert and static media

I'm building a Django app that will need SSL on all user-facing pages. On other projects where SSL was required I've run into complications when serving media files from a different virtual host on the same server. For instance the page is: https://www.mysite.com but it's referencing http://media.mysite.com/css/screen.css, and the browser subsequently displays security warnings to the user.

My understanding is that it's Django best practice to keep static files on at least their own virtual host, which -- as far as I know -- requires a subdomain like media.blahblah.com.

Obviously there's plenty of Django apps on SSL, so I must be missing something. Any advice on how this is managed?

Upvotes: 2

Views: 2015

Answers (1)

shadfc
shadfc

Reputation: 6604

The general answer is that you'll need to change the URL you're using to reference your static files to one that uses HTTPS. Using a relative path (/static/css/screen.css) instead of an absolute URL (http://...) makes your media automatically switch from HTTP to HTTPS depending on the referring page, but does force your hand when trying to serve according to best practices described below.

If you're using Django 1.3 with contrib.staticfiles, it would appear that you would just need to change the STATIC_URL setting. If not, you'll have to update the paths manually (or however you are specifying your static assets).

Best practices for static media like CSS and JavaScript do dictate that you should serve them from a webserver (not just virtualhost) different from the one serving up your Django pages. The thought there is that you can use a low-footprint webserver to serve those simple files very quickly. If you serve them from the same webserver that is running your Django site, then most likely a number of extra modules are being loaded but not used for the requests where you're just serving a static file.

Since you need to serve secured static files, you have a couple of options:

  1. You'll either need to get a separate (or wildcard) SSL certificate for your static files webserver.
    • Con: extra cost for the certificate
    • Con: you'll have to specify a different domain (instead of the relative paths described in the first paragraph) to serve your static files from.
  2. Setup SSL on a reverse proxy that handles all of the requests for your site. You're still serving your static files and Django pages from separate webservers, but the proxy knows which one to connect to based on the URL or path (ex: proxy "/static" from the static webserver, all else from the Django webserver).
    • Pro: Does allow you to use relative paths to your media.
    • Con: Extra systems configuration.

Upvotes: 4

Related Questions