光影工作室

Ubuntu下如何开启Apache的mod-rewrite模块

发布时间:5年前热度: 3173 ℃评论数:

此文背景为了解决Joomla 开启 SEF 和Apache rewrite模式后 404的问题。

要启用SEF链接支持,Apache必须开启URL重写(mod_rewrite)模块,以前修改Apache加载的模块,只需找到Apache的配置文件httpd.conf,取消相应模块的LoadModule注释行即可,如LoadModule rewrite_module。

但这次在Ubuntu下配置Apache (2.2.17),却发现老办法不行了。

 

原来,Ubuntu下的Apache 2.2 将所有已安装的模块放在 mods-available目录,将需要加载的模块链接到 mods-enabled目录,同样的,各个网站站点的配置文件放在 sites-available目录,启用的站点文件链接到 sites-enabled目录。

所以,要在Ubuntu下启用 Apache 的 rewrite模块,只需要执行以下命令:

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

然后重启Apache服务

sudo /etc/init.d/apache2 restart

此时服务器已加载mod_rewrite模块。

注意:要使指定站点启用rewrite模块,我们还需要在站点配置文件中URL重写引擎。根据Apache2的官方文档:

By default, mod_rewrite configuration settings from the main server context are not inherited by virtual hosts. To make the main server settings apply to virtual hosts, you must place the following directives in each<VirtualHost> section:

RewriteEngine On
RewriteOptions Inherit

意思是说:默认情况下mod_rewrite模块的服务器配置不会自动被其虚拟主机继承,你必须在每一个站点配置文件的<VirtualHost>单元手动添加上述代码。

所以接下来,你还需要修改自己的站点配置文件(假设就是Ubuntu下的默认站点.conf : sites-available/default.conf):

<VirtualHost *:80>
    ServerAdmin webmaster@localhost

RewriteEngine On
RewriteOptions Inherit

    DocumentRoot /var/www
    <Directory />
        Options FollowSymLinks
        AllowOverride None
    </Directory>

……..

最后,如果要使用.htaccess文件来配置你相应网站目录的重写规则(比如Joomla的官方SEF模块),那么还需要修改网站配置的AllowOverride,将上面配置文件中相应目录的 AllowOverride None 改为AllowOverride All 

apache,模块