在Ubuntu Apache中實現URL重寫,通常需要使用mod_rewrite
模塊。以下是詳細的步驟:
mod_rewrite
模塊首先,確保mod_rewrite
模塊已經啟用。你可以通過以下命令來啟用它:
sudo a2enmod rewrite
編輯你的Apache虛擬主機配置文件。通常這些文件位于/etc/apache2/sites-available/
目錄下。例如,如果你有一個名為example.com.conf
的文件,你可以使用以下命令來編輯它:
sudo nano /etc/apache2/sites-available/example.com.conf
在<VirtualHost>
塊中添加以下內容:
<VirtualHost *:80>
ServerAdmin webmaster@example.com
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
文件覆蓋配置。Require all granted
允許所有用戶訪問。.htaccess
文件在你的網站根目錄下創建或編輯.htaccess
文件。例如,如果你的網站根目錄是/var/www/html
,你可以使用以下命令來編輯它:
sudo nano /var/www/html/.htaccess
在.htaccess
文件中添加你的重寫規則。例如:
RewriteEngine On
# 將 /old-url 重寫到 /new-url
RewriteRule ^old-url$ /new-url [R=301,L]
# 將 /category/[^/]+ 重寫到 /category.php?id=$1
RewriteRule ^category/([^/]+)$ /category.php?id=$1 [L]
保存并關閉所有文件后,重啟Apache服務器以應用更改:
sudo systemctl restart apache2
打開瀏覽器并訪問你的網站,確保重寫規則按預期工作。例如,訪問http://example.com/old-url
應該會重定向到http://example.com/new-url
。
通過以上步驟,你應該能夠在Ubuntu Apache中成功實現URL重寫。