🌐 Apache HTTP Server
老牌穩定的模組化 Web 伺服器
Apache 是歷史最悠久的開源 HTTP 伺服器,模組化架構高度靈活,支援 .htaccess 動態設定,廣泛用於共享主機環境,與 PHP 整合最為成熟。
安裝
$ sudo apt update && sudo apt install -y apache2
sudo systemctl enable --now apache2安裝後瀏覽 http://伺服器IP 可看到 Apache 預設歡迎頁。
設定檔結構
/etc/apache2/
├── apache2.conf # 主設定檔
├── ports.conf # 監聽 port 設定
├── sites-available/ # 虛擬主機設定檔
│ └── 000-default.conf # 預設站台
├── sites-enabled/ # 啟用的站台(symlink)
├── mods-available/ # 可用模組
└── mods-enabled/ # 已啟用模組(symlink)虛擬主機設定
$ sudo vim /etc/apache2/sites-available/example.com.conf
ServerName example.com
ServerAlias www.example.com
DocumentRoot /var/www/example.com
Options -Indexes FollowSymLinks
AllowOverride All # 允許 .htaccess
Require all granted
ErrorLog ${APACHE_LOG_DIR}/example.com.error.log
CustomLog ${APACHE_LOG_DIR}/example.com.access.log combined
$ sudo a2ensite example.com.conf
sudo a2dissite 000-default.conf
sudo apachectl configtest && sudo systemctl reload apache2常用模組
| 模組 | 用途 | 啟用 |
|---|---|---|
mod_rewrite | URL 重寫(.htaccess 必備) | sudo a2enmod rewrite |
mod_ssl | HTTPS 支援 | sudo a2enmod ssl |
mod_headers | 修改 HTTP 標頭 | sudo a2enmod headers |
mod_deflate | Gzip 壓縮回應 | sudo a2enmod deflate |
mod_expires | 靜態資源快取控制 | sudo a2enmod expires |
mod_proxy | 反向代理 | sudo a2enmod proxy proxy_http |
啟用或停用模組後需
sudo systemctl restart apache2 才能生效。
.htaccess 常用設定
# 需要 AllowOverride All 且已啟用 mod_rewrite
RewriteEngine On
# 所有請求導向 index.php(PHP 框架必備)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [L]
# 強制 HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
# 靜態資源快取
ExpiresActive On
ExpiresByType image/webp "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
常用操作
| 操作 | 指令 |
|---|---|
| 測試設定語法 | sudo apachectl configtest |
| 重新載入設定(不中斷) | sudo systemctl reload apache2 |
| 完全重啟 | sudo systemctl restart apache2 |
| 即時查看錯誤日誌 | sudo tail -f /var/log/apache2/error.log |
| 列出已啟用模組 | apache2ctl -M |
常見問題
✕ AH00558: Could not reliably determine server's fully qualified domain name
- 原因
- 未設定 ServerName,Apache 無法確定主機名稱。
- 解法
- 在
/etc/apache2/apache2.conf末尾加入ServerName localhost,再 reload。
✕ .htaccess 重寫規則無效
- 原因
- Directory 區塊中
AllowOverride None,或mod_rewrite未啟用。 - 解法
- 將設定改為
AllowOverride All,並執行sudo a2enmod rewrite && sudo systemctl restart apache2。