在Ubuntu上使用Apache2的mod_rewrite
模塊可以幫助你實現URL重寫和重定向。以下是如何啟用和使用mod_rewrite
的步驟:
mod_rewrite
模塊首先,你需要確保mod_rewrite
模塊已經啟用。你可以使用以下命令來啟用它:
sudo a2enmod rewrite
接下來,你需要配置Apache2以允許使用.htaccess
文件進行重寫規則。編輯你的虛擬主機配置文件(通常位于/etc/apache2/sites-available/
目錄下),添加或修改以下內容:
<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
文件在你的網站根目錄(例如/var/www/html
)下創建或編輯.htaccess
文件,添加你的重寫規則。以下是一個簡單的示例:
RewriteEngine On
RewriteBase /
# 將所有請求重寫到index.php
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
這個示例將所有非文件和非目錄的請求重寫到index.php
。
保存你的更改并重啟Apache2服務器以使配置生效:
sudo systemctl restart apache2
你可以通過訪問你的網站來驗證配置是否生效。例如,如果你有一個簡單的PHP文件index.php
,你應該能夠通過瀏覽器訪問它。
重定向HTTP到HTTPS:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
重寫URL路徑:
RewriteEngine On
RewriteRule ^old-page$ /new-page [R=301,L]
重寫查詢參數:
RewriteEngine On
RewriteCond %{QUERY_STRING} ^id=(\d+)$
RewriteRule ^product$ /product.php?id=%1 [L]
通過這些步驟,你應該能夠在Ubuntu上使用Apache2的mod_rewrite
模塊來實現URL重寫和重定向。