Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學

Windows 7 下以 Apache + mod_wsgi 部署 Django 專案完整實戰教學

編輯:Windows 7 系統介紹

在 Windows 7 部署 Django 專案至 Apache,推薦使用 mod_wsgi 模組(較 mod_python 現代、效能更好)。以下為實戰部署全紀錄:

環境準備

  • Windows 7、Apache 2.2(安裝路徑 C:\Program Files (x86)\Apache Software Foundation\Apache2.2)、Python 2.7、Django 專案(範例路徑 D:\OPSAPP\appops)。
  • 下載 mod_wsgi-3.4.ap22.win32-py2.7 → 解壓取出 mod_wsgi.so → 放入 Apache modules 目錄。

關鍵配置檔案

1. Django 專案根目錄建立 django.wsgi

#coding=utf-8
import os, sys
import django.core.handlers.wsgi
os.environ["DJANGO_SETTINGS_MODULE"] = "appops.settings"
app_path = "D:/OPSAPP/appops"
sys.path.append(app_path)
application = django.core.handlers.wsgi.WSGIHandler()

2. 專案根目錄建立 apache_django_wsgi.conf

Alias /favicon.jpg D:/OPSAPP/appops/static/images/favicon.jpg
WSGIScriptAlias / "D:/OPSAPP/django.wsgi"
WSGIPassAuthorization On

    Order Deny,Allow
    Allow from all

Alias /static/ D:/OPSAPP/appops/static/

    Order deny,allow
    Allow from all
    IndexOptions FancyIndexing


    Order deny,allow
    Allow from all
    IndexOptions FancyIndexing


    Allow from all

3. 編輯 Apache httpd.conf

LoadModule wsgi_module modules/mod_wsgi.so
Alias /static D:/OPSAPP/appops/static

    SetHandler None


    ServerName app.ops.test.com
    DocumentRoot D:/OPSAPP
    WSGIScriptAlias / D:/OPSAPP/django.wsgi
    
        Order deny,allow
        Allow from all
    
    
        Allow from all
    


    Order Deny,Allow
    Allow from all

目錄結構參考

D:/OPSAPP/
├── django.wsgi
├── apache_django_wsgi.conf
└── appops/
    ├── settings.py
    ├── appops/
    └── static/

常見錯誤與解決

  1. 靜態資源 404(CSS/JS 不生效):httpd.conf 必須加入 <Directory D:/OPSAPP/appops/static/> Allow from all 區塊。
  2. 找不到模組:路徑錯誤(檢查 sys.path、DJANGO_SETTINGS_MODULE)或檔案命名與 Django/Python 內建模組衝突(避免命名為 django.py、settings.py 等)。
  3. 錯誤日誌位置:C:\Program Files (x86)\Apache Software Foundation\Apache2.2\logs\error.log。

重啟 Apache 服務後,造訪 https://app.ops.test.com(或配置 hosts 對應本機 IP)即可存取 Django 專案。路徑大小寫、斜線方向、虛擬主機名稱需與實際環境一致,部署前建議逐項核對。

Copyright © Windows教程網 All Rights Reserved