.htaccess(Hypertext Access)是 Apache 的目錄級設定檔,允許在無根權限下覆寫主設定,常用於:URL 重寫、存取控制、自訂錯誤頁、快取策略、強制 HTTPS 等。
httpd.conf(通常位於 /etc/httpd/conf/ 或 /usr/local/apache/conf/)。<Directory> 區塊,例如:<Directory /var/www/html>
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
AllowOverride None 改為 AllowOverride All:AllowOverride All
# CentOS/RHEL systemctl restart httpd # Ubuntu/Debian systemctl restart apache2
| 值 | 允許覆寫的指令類別 |
|---|---|
| None | 完全禁止 .htaccess |
| AuthConfig | 認證授權指令 |
| FileInfo | 文件類型、編碼、重寫、重定向 |
| Indexes | 目錄索引 |
| Limit | 存取控制 |
| Options | 目錄選項 |
| All | 以上全部 |
生產環境建議最小權限原則,例如僅需 URL 重寫可設 AllowOverride FileInfo。
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https://(www\.)?yourdomain\.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [F,NC]
httpd.conf 或 vhost.conf。apachectl configtest 驗證。rename txt .htaccess。