将所有url重写为索引,并将path作为GET变量


Rewrite all URLs to index with path as GET variable

我试图将其他index.php文件的所有请求转发到根index.php文件,其路径编码为GET变量。以下是我的意思的一些例子:

http://my-site.com/this/is/the/path/index.php将变成:http://my-site.com/?path=%2Fthis%2Fis%2Fthe%2Fpath%2Findex.php

http://my-site.com/this/is/the/path/将变成:http://my-site.com/?path=%2Fthis%2Fis%2Fthe%2Fpath%2F

http://my-site.com/this/is/the/path/index.php?v=var将变成:http://my-site.com/?path=%2Fthis%2Fis%2Fthe%2Fpath%2Findex.php%3Fv%3Dvar

如何用。htaccess文件完成?

编辑明确地说,以下是我希望实现的目标:

  • 如果路径是一个名为"index.php"它重定向,只要它不是根索引文件。注意,上面所说的index.php文件可以包含GET变量。
  • 如果路径以斜杠结尾,只要它不是根目录,就应该重定向。同样,注意说的路径可以包含GET变量。
  • 否则,它不应该重定向任何其他路径。

总而言之,只有指向index.php文件的路径(不是根)或以斜杠结尾的路径才应该被重定向。

将此代码放入您的DOCUMENT_ROOT/.htaccess文件:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ /index.php?path=$1 [L,QSA]

你可以使用这个。htaccess文件

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule (.*) index.php?path=$1 [L]
</IfModule>

我建议在Apache的mod_rewrite中学习一点正则表达式。

RewriteEngine On
RewriteRule ^(.*/index.php)$ index.php?path=$1

注意,这将只重写以index.php结尾的URL,而保留所有其他URL,因为这是您指定的行为。如果你想重写所有的URL索引:

RewriteEngine On
RewriteRule ^(.*)$ index.php?path=$1