在 Apache2 中,URL 重寫通常是通過使用 mod_rewrite
模塊來實現的。這個模塊允許你根據特定的規則修改請求的 URL。以下是實現 URL 重寫的基本步驟:
啟用 mod_rewrite 模塊:
確保 mod_rewrite
模塊已經啟用。你可以使用以下命令來啟用它:
sudo a2enmod rewrite
配置 Apache 配置文件:
你需要在 Apache 的配置文件中啟用 URL 重寫。通常,這可以在虛擬主機配置文件中完成。例如,如果你使用的是 /etc/apache2/sites-available/your-site.conf
,你可以添加以下內容:
<VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html
<Directory /var/www/html>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
注意 AllowOverride All
這一行,它允許 .htaccess
文件中的重寫規則生效。
創建或編輯 .htaccess 文件:
在你的網站根目錄下創建或編輯 .htaccess
文件,并添加重寫規則。例如:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
# 重寫規則示例:將 /old-url 重寫到 /new-url
RewriteRule ^old-url$ /new-url [R=301,L]
# 另一個示例:將所有請求重寫到 index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [L]
</IfModule>
解釋:
RewriteEngine On
:啟用重寫引擎。RewriteBase /
:設置重寫的基礎路徑。RewriteRule ^old-url$ /new-url [R=301,L]
:將 /old-url
重寫到 /new-url
,并使用 301 重定向。RewriteCond %{REQUEST_FILENAME} !-f
和 RewriteCond %{REQUEST_FILENAME} !-d
:檢查請求的文件或目錄是否存在。RewriteRule ^(.*)$ index.php [L]
:將所有請求重寫到 index.php
。重啟 Apache 服務器:
保存 .htaccess
文件后,重啟 Apache 服務器以使更改生效:
sudo systemctl restart apache2
通過以上步驟,你就可以在 Apache2 中實現 URL 重寫了。根據你的具體需求,可以編寫不同的重寫規則。