🌐 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_rewriteURL 重寫(.htaccess 必備)sudo a2enmod rewrite
mod_sslHTTPS 支援sudo a2enmod ssl
mod_headers修改 HTTP 標頭sudo a2enmod headers
mod_deflateGzip 壓縮回應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