从子目录内重写 PHP 参数的 URL


Rewriting a URL to a PHP parameter from inside a subdirectory

我要求的只是将任何URL给定的子方向重写为PHP URL参数,以获得更好看,用户友好的URL。

我知道使用 Apache 重写引擎和相关参数可以实现这一点。我这边的问题是我不想重写,即

mydomain.com/parameter ----------->
mydomain.com/index.php?id=parameter 

但是重写

mydomain.com/subdirectory/parameter ----------->
mydomain.com/subdirectory/index.php?id=parameter

在我的根文件夹中,我有一个用于 404 错误等的 .htaccess 文件,将不存在的页面重定向到主页面。在我完成的测试中,我已经停用了这些认为它们可以覆盖另一个.htaccess文件。我试过了。。。

RewriteEngine On
RewriteRule ^directory/([^/'.]+)/?$ index.php?id=$1 [L]

。以及其他与此类似的片段。

包含此代码的 .htaccess 文件被放置在根/目录文件夹中。我想实现的是将root/directory/string重定向到root/directory/index.php?id=string。

由于我对.htaccess和重写的了解显然有限,我需要回答两个问题。

  1. 根文件夹中的 404 重写器是否会覆盖子目录中的任何其他重写器?

  2. 如何实现我所追求的?(很像 url 缩短器的工作方式 - bit.ly/shortened)来自子目录?

此规则应该适用于您的DOCUMENT_ROOT/.htaccess文件:

RewriteEngine On
RewriteRule ^(directory)/([^/.]+)/?$ /$1/index.php?id=$2 [L,NC,QSA]

确保 directory 中没有其他.htaccess文件。