一、Ubuntu 默认未开启 Rewrite 支持
apche
模块加载工作已分散到不同的配置文件,这样看起来似乎更为合理,管理起来也非常方便。下面看一下如何开启
Rewrite 模块,当用户需使用 301 重定向、伪静态等 Rewrite
功能时,一般都习惯于使用.htaccess 文件配置,比如下面的 301
重定向:
Options +FollowSymLinks
RewriteEngine on
RewriteCond
%{HTTP_HOST} ^abc.com [NC]
RewriteRule ^(.*)$
http://www.abc.com/$1 [L,R=301]
配置完成后,使用 /etc/init.d/apache2 reload
命令加载生效,这时,如果未开启 Rewrite 功能,则会出现 500
错误(浏览器显示),查看 LOG 错误如下:
[Sun Jan 30 02:41:29
2011] [alert] [client 12.34.56.78]
/srv/www/abc.com/public_html/.htaccess: Invalid command
‘RewriteEngine’, perhaps misspelled or defined by a
module not included in the server configuration
说明需要开启
Rewrite 模块加载,加载开启过程如下。
二、手动开启加载 Rewrite
1、使用终端工具连接服务器,输入管理员帐号和密码
2、执行加载
Rewrite 模块:
a2enmod rewrite
执行后,会提示 OK 和重启
Apache 命令(/etc/init.d/apache2 restart)。
3、参照上文的目录配置,做个启动链接(下次启动自动加载):
ln
-s /etc/apache2/mods-available/rewrite.load
/etc/apache2/mods-enabled/rewrite.load
执行后会在
mods-available 目录下创建一个快捷方式,连接到 mods-enabled 下
rewrite 模块。
4、重启 apache:
/etc/init.d/apache2
restart
注意:如果使用的是 apache 默认网站目录 (一般是类似于
/var/www 文件夹),没有创建单独的自己配置文件,可能还需要修改
/etc/apache2/sites-available/default 这个文件,把其中的
AllowOverride None 修改为 AllowOverride All,因为 default
配置里还默认关闭.htaccess 重载,打开后.htaccess 才会生效。
三、如何判断 Rewrite 已经开启
1、检查确认 Rewrite 模块加载
本文测试是在 CentOS 6
系统上,路径为:/etc/httpd/conf/httpd.conf
LoadModule
rewrite_module modules/mod_rewrite.so
如果前面有注释就去掉即可,重启
APACHE。
2、检查确认目录 Rewrite 打开
Rewrite 库加载不代表我们的.htaccess
文件就能生效,还需要专门打开指定目录的 AllowOveride
开关,脚本如下:
<Directory /var/www/>
Options
Indexes FollowSymLinks
AllowOverride All
Order
allow,deny
Allow from all
</Directory>
其中
AllowOverride 只能定义在 Directory 这个 Section 里,具体用法可参考
apache 官方说明(下文链接),以上脚本一般放在 httpd.conf 或
/etc/httpd/conf.d/vhost.conf 下面,尽量更网站配置的:
<VirtualHost
…> ….</VirtualHost>
定义在一起,方便维护。
3、测试 Rewrite 功能
以下为.htaccess 测试实例:
# BEGIN
<IfModule
mod_rewrite.c>
RewriteEngine on
RewriteBase /
RewriteRule
.*$ http://www.metsky.com
</IfModule>
#END
测试方法,拷贝保存为.htaccess,上传到网站根目录下,访问网站任何路径页面,均会跳转到本博客,说明 Rewrite 已生效。