如何在 Debian 或 Ubuntu 上的 Apache2 中启用 mod_rewrite
如果您在 Ubuntu 或 Debian 系统上通过 apt-get 或 aptitude 安装了 Apache HTTP 服务器,则它已安装 mod_rewrite 模块,但默认情况下未启用。安装 Apache Web 服务器后,您需要显式启用 mod_rewrite
才能享受其好处。
什么是mod_rewrite
?
Apache HTTP Web 服务器拥有通过可插入模块的概念实现的可扩展功能。在构建 Apache Web 服务器时,您编译了一组您认为必要的模块,并将它们构建到 Web 服务器中。其中一个模块称为 mod_rewrite
,它负责在服务器端动态重写网站 URL。例如,当用户请求 http://myserver.com/my_category/my_post.html
时,请求的 URL 可以通过 mod_rewrite
转换为 http://myserver.com/post.php?category=100&post=200
,然后由 Web 服务器的后端引擎处理。
为什么使用mod_rewrite?
网站管理员通常使用 mod_rewrite
通过向世界公开更容易记住和更容易抓取的 URL 来提高网站的用户友好性和搜索引擎友好性。此外,它还可以帮助隐藏任何敏感信息,例如 URL 请求中的查询字符串,从而增强网站安全性。
如何在 Apache2 上启用 mod_write
Apache2 默认安装了 mod_rewrite
。要检查是否是这种情况,请验证 /etc/apache2/mods-available/rewrite.load
是否存在。
$ cat /etc/apache2/mods-available/rewrite.load
LoadModule rewrite_module /usr/lib/apache2/modules/mod_rewrite.so
要在 Apache2 Web 服务器中启用并加载 mod_rewrite
,请执行其余步骤。
$ sudo a2enmod rewrite
上面的命令将在 /etc/apache2/mods-enabled
中创建一个符号链接。
$ ls -al /etc/apache2/mods-enabled/rewrite.load
lrwxrwxrwx 1 root root 30 Dec 9 23:10 /etc/apache2/mods-enabled/rewrite.load -> ../mods-available/rewrite.load
然后打开以下文件,并将每次出现的 AllowOverride None
替换为 AllowOverride all
。
$ sudo vi /etc/apache2/sites-available/default
最后,重新启动Apache2。
在 Ubuntu 14.10 或 Debian 7 或更早版本上:
$ sudo service apache2 restart
在 Ubuntu 15.04 或 Debian 8 或更高版本上:
$ sudo systemctl start apache2