배포 전 체크리스트¶
인터넷은 적대적인 환경입니다. 여러분의 장고 프로젝트를 배포하기 전에, 보안과 성능, 연산에 관련해서 설정을 다시 살펴볼 시간이 필요합니다.
장고는 보안 기능을 많이 갖고 있습니다. 몇몇은 내장된 기능으로 항상 켜져있습니다. 다른 몇몇은 선택할 수 있는데 그 이유는 항상 보안 기능들이 적절하지 않거나 개발에 불편함을 가져올 수 있기 때문입니다. 예를 들어 강제로 HTTPS를 활성화 하는 것은 모든 웹사이트에 적합하지 않을 수도 있고, 로컬 개발환경에선 비실용적일 수도 있습니다.
성능 최적화는 편의를 위한 또다른 범주의 거래입니다. 예를 들어, 캐싱은 상용 환경에서 유용할 수 있지만 로컬 개발 환경에서는 실용적이지 않을 수 있습니다. 오류 보고의 필요성에도 큰 차이가 있습니다.
설정에 대한 체크리스트는 다음과 같습니다.
- Django에서 예상되는 수준의 보안을 제공하도록 설정해야 합니다.
- 각 환경에 맞도록 설정해야 합니다.
- 선택적인 보안 기능들을 활성화시켜야 합니다.
- 성능 최적화가 적용돼야 합니다.
- 에러 보고가 제공되어야 합니다.
이 설정들 중 대부분은 예민할 수 있고 감추어져야 합니다. 만약 여러분이 프로젝트의 소스코드를 배포한다면, 대부분은 개발 환경에 최적화된 설정으로 배포하고 상용 환경에서 사용할 별도의 설정을 사용할 것입니다.
manage.py check --deploy
명령 실행¶
Some of the checks described below can be automated using the check
--deploy
option. Be sure to run it against your production settings file as
described in the option's documentation.
Critical settings¶
SECRET_KEY
¶
The secret key must be a large random value and it must be kept secret.
Make sure that the key used in production isn't used anywhere else and avoid committing it to source control. This reduces the number of vectors from which an attacker may acquire the key.
Instead of hardcoding the secret key in your settings module, consider loading it from an environment variable:
import os
SECRET_KEY = os.environ['SECRET_KEY']
or from a file:
with open('/etc/secret_key.txt') as f:
SECRET_KEY = f.read().strip()
DEBUG
¶
You must never enable debug in production.
You're certainly developing your project with DEBUG = True
,
since this enables handy features like full tracebacks in your browser.
For a production environment, though, this is a really bad idea, because it leaks lots of information about your project: excerpts of your source code, local variables, settings, libraries used, etc.
Environment-specific settings¶
ALLOWED_HOSTS
¶
When DEBUG = False
, Django doesn't work at all without a
suitable value for ALLOWED_HOSTS
.
This setting is required to protect your site against some CSRF attacks. If
you use a wildcard, you must perform your own validation of the Host
HTTP
header, or otherwise ensure that you aren't vulnerable to this category of
attacks.
You should also configure the Web server that sits in front of Django to validate the host. It should respond with a static error page or ignore requests for incorrect hosts instead of forwarding the request to Django. This way you'll avoid spurious errors in your Django logs (or emails if you have error reporting configured that way). For example, on nginx you might setup a default server to return "444 No Response" on an unrecognized host:
server {
listen 80 default_server;
return 444;
}
CACHES
¶
If you're using a cache, connection parameters may be different in development and in production. Django defaults to per-process local-memory caching which may not be desirable.
Cache servers often have weak authentication. Make sure they only accept connections from your application servers.
If you're using Memcached, consider using cached sessions to improve performance.
DATABASES
¶
Database connection parameters are probably different in development and in production.
Database passwords are very sensitive. You should protect them exactly like
SECRET_KEY
.
For maximum security, make sure database servers only accept connections from your application servers.
If you haven't set up backups for your database, do it right now!
STATIC_ROOT
and STATIC_URL
¶
Static files are automatically served by the development server. In
production, you must define a STATIC_ROOT
directory where
collectstatic
will copy them.
See Managing static files (e.g. images, JavaScript, CSS) for more information.
MEDIA_ROOT
and MEDIA_URL
¶
Media files are uploaded by your users. They're untrusted! Make sure your web
server never attempts to interpret them. For instance, if a user uploads a
.php
file, the web server shouldn't execute it.
Now is a good time to check your backup strategy for these files.
FILE_UPLOAD_PERMISSIONS
¶
With the default file upload settings, files smaller than
FILE_UPLOAD_MAX_MEMORY_SIZE
may be stored with a different mode
than larger files as described in FILE_UPLOAD_PERMISSIONS
.
Setting FILE_UPLOAD_PERMISSIONS
ensures all files are uploaded with
the same permissions.
HTTPS¶
Any website which allows users to log in should enforce site-wide HTTPS to avoid transmitting access tokens in clear. In Django, access tokens include the login/password, the session cookie, and password reset tokens. (You can't do much to protect password reset tokens if you're sending them by email.)
Protecting sensitive areas such as the user account or the admin isn't sufficient, because the same session cookie is used for HTTP and HTTPS. Your web server must redirect all HTTP traffic to HTTPS, and only transmit HTTPS requests to Django.
Once you've set up HTTPS, enable the following settings.
CSRF_COOKIE_SECURE
¶
Set this to True
to avoid transmitting the CSRF cookie over HTTP
accidentally.
SESSION_COOKIE_SECURE
¶
Set this to True
to avoid transmitting the session cookie over HTTP
accidentally.
Performance optimizations¶
Setting DEBUG = False
disables several features that are
only useful in development. In addition, you can tune the following settings.
CONN_MAX_AGE
¶
Enabling persistent database connections can result in a nice speed-up when connecting to the database accounts for a significant part of the request processing time.
This helps a lot on virtualized hosts with limited network performance.
TEMPLATES
¶
Enabling the cached template loader often improves performance drastically, as it avoids compiling each template every time it needs to be rendered. See the template loaders docs for more information.
Error reporting¶
By the time you push your code to production, it's hopefully robust, but you can't rule out unexpected errors. Thankfully, Django can capture errors and notify you accordingly.
LOGGING
¶
Review your logging configuration before putting your website in production, and check that it works as expected as soon as you have received some traffic.
See 로깅 for details on logging.
ADMINS
and MANAGERS
¶
ADMINS
will be notified of 500 errors by email.
MANAGERS
will be notified of 404 errors.
IGNORABLE_404_URLS
can help filter out spurious reports.
See Error reporting for details on error reporting by email.
Error reporting by email doesn't scale very well
Consider using an error monitoring system such as Sentry before your inbox is flooded by reports. Sentry can also aggregate logs.
Customize the default error views¶
Django includes default views and templates for several HTTP error codes. You
may want to override the default templates by creating the following templates
in your root template directory: 404.html
, 500.html
, 403.html
, and
400.html
. The default error views that use these
templates should suffice for 99% of Web applications, but you can
customize them as well.