---
title: "如何使用 Apache 和 mod_wsgi 托管 Django"
version: 3.0
locale: zh-hans
source: https://docs.djangoproject.com/zh-hans/3.0/howto/deployment/wsgi/modwsgi/
canonical: https://djangodocs.dev/zh-hans/3.0/howto/deployment/wsgi/modwsgi/
---
# 如何使用 Apache 和 `mod_wsgi` 托管 Django

利用 [Apache](https://httpd.apache.org/) 和 [mod\_wsgi](https://modwsgi.readthedocs.io/en/develop/) 在生产环境部署已经过充分测试。

mod\_wsgi 是一个 Apache 模块，它可以管理任何 Python [WSGI](https://wsgi.readthedocs.io/en/latest/) 应用，包括 Django。Django 支持所有支持 mod\_wsgi 的 Apache 版本。

[官方 mod\_wsgi 文档](https://modwsgi.readthedocs.io/) 介绍了如何使用 mod\_wsgi 的全部细节。你可能更喜欢从 [安装和配置文档](https://modwsgi.readthedocs.io/en/develop/installation.html) 开始。

## 基础配置

Once you've got mod\_wsgi installed and activated, edit your Apache server's
[httpd.conf](https://wiki.apache.org/httpd/DistrosDefaultLayout) file and add the following.

```apache
WSGIScriptAlias / /path/to/mysite.com/mysite/wsgi.py
WSGIPythonHome /path/to/venv
WSGIPythonPath /path/to/mysite.com

<Directory /path/to/mysite.com/mysite>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
```

`WSGIScriptAlias` 行的第一项是你所期望的应用所在的基础 URL 路径（ `/` 根 url），第二项是 "WSGI 文件" 的位置——一般位于项目包之内（本例中是 `mysite`）。这告诉 Apache 用该文件中定义的 WSGI 应用响应指定 URL 下的请求。

If you install your project's Python dependencies inside a [`virtual
environment`](https://docs.python.org/3/library/venv.html#module-venv), add the path using `WSGIPythonHome`. See the [mod\_wsgi
virtual environment guide](https://modwsgi.readthedocs.io/en/develop/user-guides/virtual-environments.html) for more details.

`WSGIPythonPath` 行确保你的项目包能从 Python path 导入；换句话说， `import mysite` 能正常工作。

The `<Directory>` piece ensures that Apache can access your `wsgi.py`
file.

下一步，我们需要确认 `wsgi.py` 文件包含一个 WSGI 应用对象。从 Django 1.4 起， [`startproject`](/zh-hans/3.0/ref/django-admin/#django-admin-startproject) 会自动创建；换而言之，你无需手动创建。查阅 [WSGI 概述文档](/zh-hans/3.0/howto/deployment/wsgi/) 获取你需要配置的默认内容，以及其它可配置项。

> **Warning**
>
> 如果多个 Django 站点运行在同一 mod\_wsgi 进程，它们会共用最先启动的站点配置。能通过以下修改改变行为:
>
> ```
> os.environ.setdefault("DJANGO_SETTINGS_MODULE", "{{ project_name }}.settings")
> ```
>
> `wsgi.py` 中也这么改:
>
> ```
> os.environ["DJANGO_SETTINGS_MODULE"] = "{{ project_name }}.settings"
> ```
>
> 或通过 [使用 mod\_wsgi 的后台模式](#daemon-mode) 确保每个站点都运行于独立的后台进程。

> **为文件上传修复 UnicodeEncodeError**
>
> 上传名称包含非 ASCII 字符的文件时，若抛出 `UnicodeEncodeError`，确认 Apache 是否被正确配置，能接受非 ASCII 文件名:
>
> ```
> export LANG='en_US.UTF-8'
> export LC_ALL='en_US.UTF-8'
> ```
>
> 常见的配置文件路径是 `/etc/apache2/envvars`。
>
> 参考 Unicode 参考指引的 [Files](/zh-hans/3.0/ref/unicode/#unicode-files) 章节获取细节信息。

## 使用 `mod_wsgi` 后台模式

"Daemon mode" 是运行 mod\_wsgi 的推荐模式（在非 Windows 平台上）。为了创建必要的后台进程组并在其中运行 Django 实例，你需要添加合适的 `WSGIDaemonProcess` 和 `WSGIProcessGroup` 指令。上述配置在你使用后台模式时需要点小修改，即你不能使用 `WSGIPythonPath`；作为替换，你要在 `WSGIDaemonProcess` 中添加 `python-path` 选项，例如：

```apache
WSGIDaemonProcess example.com python-home=/path/to/venv python-path=/path/to/mysite.com
WSGIProcessGroup example.com
```

如果你想在子目录中开放你的项目（本例中 `https://example.com/mysite`），你可在上述配置中添加 `WSGIScriptAlias`：

```apache
WSGIScriptAlias /mysite /path/to/mysite.com/mysite/wsgi.py process-group=example.com
```

参考官方 mod\_wsgi 文档获取 [配置后台模式的细节](https://modwsgi.readthedocs.io/en/develop/user-guides/quick-configuration-guide.html#delegation-to-daemon-process)。

## 提供文件服务

Django 本身并不提供文件服务；他将这个职责交给了你选择的 Web 服务器。

我们推荐使用一个独立的 Web 服务器，即其未运行 Django——仅用于媒体服务。以下是一些不错的选项：

- [Nginx](https://nginx.org/en/)
- 一个 [Apache](https://httpd.apache.org/) 的朴素版本

然而，若你别无选择，只能在与 Django 相同的 Apache `VirtualHost` 上提供媒体文件，你可以让 Apache 为一些 URL 提供静态媒体服务，其它的用 mod\_wsgi 接口传递给 Django。

本例在站点根目录配置 Django，但以静态文件的形式提供 `robots.txt`， `favicon.ico` 以及 `/static/` 和 `/media/` 中的内容。其它所有 URL 以 mod\_wsgi 提供服务：

```apache
Alias /robots.txt /path/to/mysite.com/static/robots.txt
Alias /favicon.ico /path/to/mysite.com/static/favicon.ico

Alias /media/ /path/to/mysite.com/media/
Alias /static/ /path/to/mysite.com/static/

<Directory /path/to/mysite.com/static>
Require all granted
</Directory>

<Directory /path/to/mysite.com/media>
Require all granted
</Directory>

WSGIScriptAlias / /path/to/mysite.com/mysite/wsgi.py

<Directory /path/to/mysite.com/mysite>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
```

## 服务后台文件

[`INSTALLED_APPS`](/zh-hans/3.0/ref/settings/#std-setting-INSTALLED_APPS) 中包含 [`django.contrib.staticfiles`](/zh-hans/3.0/ref/contrib/staticfiles/#module-django.contrib.staticfiles) 时，Django 开发服务器自动为这些归属于后台应用（也包含其它已安装的应用）的静态文件提供服务。这与你使用其它服务器时不太一样。你需要正确配置 Apache 或其它你使用的 Web 服务器，另其正确的为后台文件提供服务。

后台文件位于 Django 发行版的 (`django/contrib/admin/static/admin`) 中。

我们 **强烈** 建议用 [`django.contrib.staticfiles`](/zh-hans/3.0/ref/contrib/staticfiles/#module-django.contrib.staticfiles) 处理后台文件（连同上一节所述的 Web 服务器；这意味着用 [`collectstatic`](/zh-hans/3.0/ref/contrib/staticfiles/#django-admin-collectstatic) 管理命令收集 [`STATIC_ROOT`](/zh-hans/3.0/ref/settings/#std-setting-STATIC_ROOT) 中的静态文件，然后配置 Web 服务器，使其在 [`STATIC_URL`](/zh-hans/3.0/ref/settings/#std-setting-STATIC_URL) 为 [`STATIC_ROOT`](/zh-hans/3.0/ref/settings/#std-setting-STATIC_ROOT) 提供服务），不过，这还有几个方法：

1. 在文档根目录中创建一个指向后台静态文件的符号链接（Apache 配置中可能要添加 `+FollowSymLinks`）。
2. 使用前文介绍的 `Alias` 指令，为合适的 URL (可能是 [`STATIC_URL`](/zh-hans/3.0/ref/settings/#std-setting-STATIC_URL) \+ `admin/`) 取个别名，指向后台文件的实际位置。
3. 直接将后台静态文件拷贝至 Apache 的文档根目录。

## Apache 利用 Django 的用户数据库进行验证

Django 提供了一个处理器，允许 Apache 直接用 Django 的认证授权后端认证用户。参考文档 [mod\_wsgi 认证授权文档](/zh-hans/3.0/howto/deployment/wsgi/apache-auth/)。
