Mod 不用 .htaccess 重写

Mod rewrite without .htaccess

假设我有一个名为

的网站
foo.com

我可以访问 foo.com,它 运行 是在根文件夹中找到的 index.php。我的问题是:我应该如何编辑 vhost 文件以在不启用 htaccess 的情况下启用重写 mod?

我的目标是能够写作

http://foo.com/bar/loremipsum/dolor

进入我的浏览器地址栏并 运行 index.php 不管 url 中的 / 字符数。我的 index.php 将处理由 /

分隔的参数

我怎样才能做到这一点?

编辑: 虚拟主机文件:

<VirtualHost *:80>
        ServerName myproject.com
        ServerAlias www.myproject.com

        ServerAdmin webmaster@localhost
        DocumentRoot /opt/apps/myproject

        <Directory /opt/apps/myproject>
            # disable htaccess
            AllowOverride None

            # route everything to index.php
            RewriteCond %{REQUEST_FILENAME} !-f
            RewriteCond %{REQUEST_FILENAME} !-d
            RewriteRule ^ /index.php [L]

            Require all granted
        </Directory>
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

编辑:问题,正如接受的答案所暗示的那样,该主机不包含打开重写引擎的行。此行出现在答案中。这解决了问题。

要禁止使用 htaccess,您需要在文档根目录的 <Directory> 容器中使用此指令,然后您只需将 mod_rewrite 规则放在同一容器中即可:

<Directory "/var/www/htdocs/">
    # disable htaccess
    AllowOverride None

    # route everything to index.php
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^ /index.php [L]
</Directory>

假设“/var/www/htdocs”是您的文档根目录。

为确保 mod_rewrite 已加载,请检查 httpd.conf 文件中是否有包含 mod_rewrite 的 LoadModule 行,并确保它未被注释。每次更改虚拟主机配置时,您都需要重新启动服务器。

简短说明:

行:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

是检查请求是否不是现有文件 (-f) 或现有目录 (-d) 的条件。这些条件有两个主要目的:

  1. 它防止重写引擎循环,因此 index.php 也不会被重写。由于 index.php 是一个现有文件,因此条件会停止重写引擎。
  2. 它允许重写图像或脚本等资源和资产。

如果您希望 所有内容 路由到 index.php 无论如何(包括图像或其他任何内容),那么您可以将 2 个条件更改为:

RewriteCond %{REQUEST_URI} !^/index.php

以便重写除 index.php 之外的所有内容。