版本差異速查 (2.2 vs 2.4)
| 項目 | Apache 2.2 | Apache 2.4 |
| 主配置檔 | /etc/apache2/apache2.conf | 同 |
| 站點配置目錄 | /etc/apache2/sites-available/ | 同,檔名慣例 000-default.conf |
| 模組目錄 | /etc/apache2/mods-available/enabled | 同 |
| 存取控制語法 | Order allow,deny / Allow from all | Require all granted |
| MPM 配置檔 | apache2.conf 內 <IfModule mpm_prefork_module> | /etc/apache2/mods-enabled/mpm_prefork.conf |
| 預設 MPM | prefork | prefork (event/worker 可選) |
網站根目錄遷移 (避免 /var/www 需 root 權限)
Apache 2.2 (Ubuntu 12.04/Debian 7)
# 1. 編輯站點配置
vim /etc/apache2/sites-available/default
# 修改兩處:
DocumentRoot /home/user/www
<Directory /home/user/www/> # 注意結尾斜線
# 2. 重啟
service apache2 restart
Apache 2.4 (Ubuntu 13.10+/Debian 8+)
# 1. 站點配置
vim /etc/apache2/sites-available/000-default.conf
DocumentRoot /home/user/www
# 2. 主配置對應 Directory
vim /etc/apache2/apache2.conf
<Directory /home/user/www/>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
# 3. 重啟
service apache2 restart
環境變數與日誌
# 環境變數檔 (啟動腳本 source)
/etc/apache2/envvars
# 內含:APACHE_RUN_USER, APACHE_RUN_GROUP, APACHE_LOG_DIR, APACHE_PID_FILE...
# 日誌位置
/var/log/apache2/
access.log # 存取日誌
error.log # 錯誤日誌 (除錯首選)
# 手動執行 apache2 需先 source
source /etc/apache2/envvars
apache2 -t # 測試配置語法
實用 apache2 控制指令
| 指令 | 功能 |
apache2 -v | 版本資訊 |
apache2 -V | 編譯參數 (MPM、模組路徑、預設配置...) |
apache2 -l | 靜態編譯模組列表 |
apache2 -L | 所有可用配置指令說明 |
apache2 -t | 語法檢測 (修改配置後必跑) |
apache2 -T | 啟動測試 (不分離進程,前景除錯) |
模組管理機制
# 可用模組
ls /etc/apache2/mods-available/
# *.load → 模組路徑 (LoadModule)
# *.conf → 模組專屬配置
# 啟用模組 (建立軟連結)
a2enmod rewrite headers ssl proxy_fcgi
# 或手動
ln -s /etc/apache2/mods-available/rewrite.load /etc/apache2/mods-enabled/
ln -s /etc/apache2/mods-available/rewrite.conf /etc/apache2/mods-enabled/
# 停用模組
a2dismod mpm_prefork
a2enmod mpm_event # 切換 MPM 需先停用舊的
# 查看已啟用
ls -l /etc/apache2/mods-enabled/
MPM Prefork 調優參數
Apache 2.2 (apache2.conf)
<IfModule mpm_prefork_module>
StartServers 5
MinSpareServers 5
MaxSpareServers 10
MaxClients 150
MaxRequestsPerChild 0
</IfModule>
Apache 2.4 (mods-enabled/mpm_prefork.conf)
<IfModule mpm_prefork_module>
StartServers 5
MinSpareServers 5
MaxSpareServers 10
MaxRequestWorkers 150 # 取代 MaxClients
MaxConnectionsPerChild 0
# 若 MaxRequestWorkers > 256,需額外設定:
# ServerLimit 300
</IfModule>
參數含義
StartServers:啟動時建立的子進程數
Min/MaxSpareServers:閒置進程數範圍,動態調整
MaxRequestWorkers (2.4) / MaxClients (2.2):最大同步連線數 = 最大子進程數
MaxConnectionsPerChild:單進程處理請求上限,0=無限 (防記憶體洩漏建議設 10000)
監控當前進程數
ps -ef | grep apache2 | grep -v grep | wc -l
# 實際子進程數 = 結果 - 1 (父進程)
Core 模組常用參數 (apache2.conf)
| 指令 | 建議值 | 說明 |
Timeout | 300 | 請求逾時秒數 |
KeepAlive | On | 啟用持久連線 |
MaxKeepAliveRequests | 100 | 單連線最大請求數 |
KeepAliveTimeout | 5 | 持久連線等待逾時 |
常見問題排查
- 403 Forbidden:檢查
Require all granted、目錄權限 (755)、SELinux httpd_sys_content_t
- .htaccess 不生效:
AllowOverride All、模組 rewrite 已啟用
- PHP 不解析:
a2enmod php7.4、SetHandler application/x-httpd-php、檢查 dir.conf DirectoryIndex
- 配置語法錯誤:
apache2 -t 會精確報出行號