Php 使用.htaccess重写重定向URL的规则

Php 使用.htaccess重写重定向URL的规则,php,apache,.htaccess,mod-rewrite,redirect,Php,Apache,.htaccess,Mod Rewrite,Redirect,我正在使用.htaccess重定向我网站上的URL,以避免像page1.php这样的链接 我在根域上有一个子文件夹engine/index.php,我打算用它来处理重定向的URL e、 g我希望将链接localhost/user重写为localhost/engine/index.php?view=user 注意:正在使用的链接,即/user不是域上现有的文件或文件夹使用此链接: RewriteEngine On RewriteRule ^([a-z]+)$ engine/index.php?v

我正在使用
.htaccess
重定向我网站上的URL,以避免像page1.php这样的链接

我在根域上有一个子文件夹
engine/index.php
,我打算用它来处理重定向的URL

e、 g我希望将链接
localhost/user
重写为
localhost/engine/index.php?view=user
注意:正在使用的链接,即/user不是域上现有的文件或文件夹使用此链接:

RewriteEngine On

RewriteRule ^([a-z]+)$ engine/index.php?view=$1 [NC,L,QSA]
将其直接放入
www/
目录中的
.htaccess
文件中。
([a-z]+)
将匹配一组字母(由于使用了
NC
标志,因此也是大写),但如果
localhost/
后面有字母以外的内容,则不会重写url。如果
localhost
后面只有字母,则url将重写为
engine/index.php?view=$1

L
标志表示这是最后一个
重写规则
,而
QSA
标志将旧的查询字符串附加到新的查询字符串。例如:
localhost/user?var=val
将重定向到
localhost/engine/index.php?view=user&var=val

但是,如果用户转到
localhost/user?view=somethingelse
,它将被重写为
localhost/engine/index.php?view=user&view=somethingelse
,这意味着如果在
engine.php
中执行
$\u GET['view']
,它将返回“somethingelse”。要从querystring(
user
)获取第一个
视图
参数,请在PHP中使用此正则表达式:

$view = preg_replace('/view=([^&]+).*/', '$1', $_SERVER['QUERY_STRING']); //now, $view contains 'user'

到目前为止你有没有试过写规则?就是这样。谢谢@Jonan。我正在使用RewriteRule^(.*)$/engine/index.php?p=$1[L,QSA]。不确定它为什么不工作。@jmsiox可能是因为
/engine/index.php前面的
/
导致的?p=$1
。另请参阅我的更新答案,了解如何防止用户设置
视图
参数manually@T.J.Crowder现在好点了吗?;)