Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> 關於Linux

Ubuntu 上啟用 Apache Rewrite 的完整解說

在 Windows 上開啟 Apache 的 URL Rewrite 只要改一行:把 http.conf 裡 LoadModule rewrite_module modules/mod_rewrite.so 前面的註解拿掉,重啟 Apache 就完事。Ubuntu 的做法則完全不同。

一、Ubuntu 的 Apache 設定是拆開的

Debian 系的 Apache 依「目錄+檔案」組織設定,/etc/apache2 下有 conf.d、mods-available、mods-enabled、sites-available、sites-enabled 等資料夾,以及 apache2.conf、envvars、httpd.conf、magic、ports.conf 等檔案。

其中 mods-available 是「可用模組」,mods-enabled 是「目前載入的模組」;httpd.conf 預設幾乎是空的,因為載入工作被分散到各處,總入口是 apache2.conf:

# Include module configuration:
Include /etc/apache2/mods-enabled/*.load
Include /etc/apache2/mods-enabled/*.conf
# Include all the user configurations:
Include /etc/apache2/httpd.conf
# Include ports listing
Include /etc/apache2/ports.conf
# Include generic snippets of statements
Include /etc/apache2/conf.d/
# Include the virtual host configurations:
Include /etc/apache2/sites-enabled/

這種拆法看起來繁瑣,實際管理起來反而清楚。預設情況下 Rewrite 並未啟用,所以當你寫好 .htaccess 想玩 301 重定向或偽靜態時,會直接吃 500:

Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP_HOST} ^abc.com [NC]
RewriteRule ^(.*)$ https://www.shouce.ren/$1 [L,R=301]
RewriteCond %{HTTP_HOST} ^www.abc.com [NC]
RewriteRule ^(.*)$ https://www.shouce.ren/$1 [L,R=301]

用 /etc/init.d/apache2 reload 生效後,瀏覽器顯示 500,錯誤日誌會寫:

[alert] [client 12.34.56.78] /srv/www/shouce.ren/public_html/.htaccess:
Invalid command 'RewriteEngine', perhaps misspelled or defined by a module
not included in the server configuration

訊息已經說得很明白:模組沒載入。

二、手動啟用 Rewrite

1. 以管理員身分登入伺服器。

2. 執行:

a2enmod rewrite

成功後會提示 OK 以及重啟 Apache 的指令。

3. 建立載入連結(讓下次開機自動生效):

ln -s /etc/apache2/mods-available/rewrite.load /etc/apache2/mods-enabled/rewrite.load

4. 重啟:

/etc/init.d/apache2 restart

三、別忘了 AllowOverride

如果只有一個網站,且仍在使用 Apache 預設的 /var/www(沒有另建 sites-available 設定檔),還要改 /etc/apache2/sites-available/default,把 AllowOverride None 改成 AllowOverride All。因為 default 裡預設關閉 .htaccess 覆寫,不開的話 Rewrite 規則根本不會被讀取。

<VirtualHost 12.34.56.78:80>
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www
    <Directory />
        Options FollowSymLinks
        AllowOverride None
    </Directory>
    <Directory /var/www/>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Order allow,deny
        allow from all
    </Directory>
    ErrorLog /var/log/apache2/error.log
    LogLevel warn
    CustomLog /var/log/apache2/access.log combined
</VirtualHost>

存檔後重啟即可:

/etc/init.d/apache2 restart

小結:Ubuntu 上啟用 Rewrite 是「載入模組」與「允許 .htaccess 覆寫」兩件事,兩者都做到,規則才會真的生效。

Copyright © Linux教程網 All Rights Reserved