Regex htaccess中的反向mod_重写

Regex htaccess中的反向mod_重写,regex,apache,.htaccess,mod-rewrite,redirect,Regex,Apache,.htaccess,Mod Rewrite,Redirect,有没有办法用.htaccess更改url,但不重定向 我有像这样的链接 <a href="?p=hello_world">Hello World</a> 但是现在从localhost/dir/?p=hello\u-worldurl更改为localhost/hello\u-world,而没有/dir。我不知道目录的名称,因为每个人都可以使用我的项目,而无需更改其服务器上的.htaccess。您需要使用以下代码: RewriteEngine On # Determine

有没有办法用.htaccess更改url,但不重定向

我有像这样的链接

<a href="?p=hello_world">Hello World</a>

但是现在从
localhost/dir/?p=hello\u-world
url更改为
localhost/hello\u-world
,而没有
/dir
。我不知道目录的名称,因为每个人都可以使用我的项目,而无需更改其服务器上的.htaccess。

您需要使用以下代码:

RewriteEngine On

# Determine the RewriteBase dynamically (\2 is backreference for string after 1st slash
RewriteCond %{REQUEST_URI}::$1 ^(.*?/)(.*)::\2$
RewriteRule ^(.*)$ - [E=BASE:%1]

# External redirect from /dir?p=hello_world to /dir/hello_world
RewriteCond %{THE_REQUEST} \?p=([^\s&]+) [NC]
RewriteRule ^ %{ENV:BASE}%1? [R=302,L]

# Internal rewrite from /dir/hello_world to /dir/index.php?p=hello_world
RewriteRule ^([a-zA-Z0-9-]+)/?$ %{ENV:BASE}index.php?p=$1 [L,QSA]

我发现很难理解应该显示什么url,以及应该在服务器上加载什么url。不过,您需要做的是,将外部重定向(
[R,L]
标志)重定向到nice url,并将内部重写(仅
[L]
标志)重定向到旧url。对于匹配的外部重定向
%{the_REQUEST}
。可能会对您有所帮助。不幸的是,我不知道每个url应该使用的目录名称。我复制了它并更改了它?p=hello\u world to a singer/不幸的是,我不理解您的代码:/I我更改了RewriteRule
^%{ENV:BASE}/%2?[R=302,L]
重写规则^%{ENV:BASE}%1?[R=302,L]
效果很好谢谢,我根据你的评论编辑了它。如果它解决了,请考虑将答案标记为已接受。当然,我会在我的答案中加上注释。
RewriteEngine On

# Determine the RewriteBase dynamically (\2 is backreference for string after 1st slash
RewriteCond %{REQUEST_URI}::$1 ^(.*?/)(.*)::\2$
RewriteRule ^(.*)$ - [E=BASE:%1]

# External redirect from /dir?p=hello_world to /dir/hello_world
RewriteCond %{THE_REQUEST} \?p=([^\s&]+) [NC]
RewriteRule ^ %{ENV:BASE}%1? [R=302,L]

# Internal rewrite from /dir/hello_world to /dir/index.php?p=hello_world
RewriteRule ^([a-zA-Z0-9-]+)/?$ %{ENV:BASE}index.php?p=$1 [L,QSA]