mod_rewrite已启用,但无法正常工作。

我正在尝试设置一个PHP路由库。他们给出了一个.htaccess文件的示例:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L]

我无法让这个工作起来,所以我尝试启用mod_rewrite,但它显示“模块rewrite已经启用”。
为什么它不能正常工作?谢谢!我正在运行Ubuntu Precise 12.04和apache2.2.22。(检查了是否有任何更新)
编辑:还有一些细节,这是一个PuPHPet vagrant构建,应该已经启用了重写。
5个回答

你需要允许覆盖。
<Directory "/path/to/document/root/">
  AllowOverride All

</Directory>

7这是不必要的宽容。在所讨论的配置中,只有AllowOverride是必要的。Allow from All与问题无关,并且可能不适用于@randomdev的环境。 - Mark

首先,将您的httpd配置设置为以下内容(路径可能因个人而异。在我的Ubuntu中,它位于/etc/apache2/sites-available/default):
DocumentRoot /var/www

<Directory /var/www/>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride all
    Order allow,deny
    allow from all
</Directory>

在那之后,你应该使用以下命令启用 mod_rewrite
sudo a2enmod rewrite

最后一步,重新启动你的Apache服务:
sudo service apache2 restart

为了确保这一点,您可以再次从“Configuration > apache2handler > Loaded Modules”中的phpinfo检查。那里必须写着“mod_rewrite”,这意味着mod_rewrite已启用。

这个应该放在一个虚拟主机元素中吗? - jjxtra
你可以在Apache虚拟主机示例中看到一些示例。 - metamorph

我曾经遇到过类似的问题,但其他答案对我没有帮助。在.htaccess文件的开头添加了这行代码后,问题得到解决:
Options +FollowSymLinks -MultiViews

这个也没帮到我。试了这个和其他所有方法,还是得到了404错误。a2enmod显示模块已经启用,而且我也重新启动了整个服务器几次。 - bxyify

我的问题是我在文件中没有早期设置RewriteEngine on
<VirtualHost *:80>
        ServerName &URL&
        ServerAlias *.&URL&

        ServerAdmin &EMAIL_ADDRESS&

        DocumentRoot            /var/www/&URL&/public

        RewriteEngine on

        # LogLevel: Control the severity of messages logged to the error_log.
        # Available values: trace8, ..., trace1, debug, info, notice, warn,
        # error, crit, alert, emerg.
        # It is also possible to configure the log level for particular modules, e.g.
        # "LogLevel info ssl:warn"
        LogLevel                debug

        ErrorLog                /var/www/&URL&/storage/logs/apache2_error.log
        TransferLog             /var/www/&URL&/storage/logs/apache2_transfer.log

        <FilesMatch "\.(cgi|html|php)$">
                SSLOptions +StdEnvVars
        </FilesMatch>

        # <------------  Here I used to have `RewriteEngine on`

        # Handle Front Controller...
        RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME} !-f
        RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME} !-d
        RewriteRule ^ /index.php [L,QSA]

</VirtualHost>


我不知道为什么,但当我把RewriteEngine on放在更靠前的位置时,它起到了作用。

在我的情况下,我将一个网站从不同的分区移动到了Apache的分区,但是我不得不为旧位置创建一个指向该文件夹的符号链接。问题是,DocumentRoot没有更新,仍然指向旧路径,而现在是一个链接。
PS:这不是一个商业网站,只是一个内部网站,供“国内”使用。
因此,MOD_REWRITE停止工作,因为DocumentRoot没有指向新的文件夹路径,而是指向链接的末端。
[ partition A (Apache) ] <-- Folder moved  <-- [ FOLDER partition B ]

[ partition A (Apache) ] --> Symbolic link --> [ (link) partition B ]

当我将DocumentRoot更新为现在在"A"中的真实文件夹时,问题得到解决。