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

时间:2013-10-26 09:14:42

标签: php regex apache .htaccess mod-rewrite

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

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

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

但重写

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

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

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

......和其他类似的片段。

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

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

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

  2. 我如何实现我追求的目标? (很像url-shorteners如何工作 - bit.ly/shortened)来自子目录?

1 个答案:

答案 0 :(得分:3)

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

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

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