.htaccess htaccess重定向到与localhost和real domain兼容的子文件夹

.htaccess htaccess重定向到与localhost和real domain兼容的子文件夹,.htaccess,redirect,.htaccess,Redirect,我想通过htaccess将我的URL从特定子文件夹重定向到主域 一种选择是使用以下规则 RewriteRule ^subfolder/(pattern)$ http://%{HTTP_HOST}/$1 [R=301,L] 适用于实际域 redirects correctly http://example.com/subfolder/page to http://example.com/page RewriteRule ^subfolder/(pattern)$ http://%{HTTP_H

我想通过htaccess将我的URL从特定子文件夹重定向到主域

一种选择是使用以下规则

RewriteRule ^subfolder/(pattern)$ http://%{HTTP_HOST}/$1 [R=301,L]
适用于实际域

redirects correctly
http://example.com/subfolder/page
to
http://example.com/page
RewriteRule ^subfolder/(pattern)$ http://%{HTTP_HOST}/example/$1 [R=301,L]
本地主机的工作方式不正确

redirects
http://localhost/exmple/subfolder/page
to
http://localhost/page
instead of 
http://localhost/exmple/page
按如下方式修改规则适用于localhost,但不适用于实际域

redirects correctly
http://example.com/subfolder/page
to
http://example.com/page
RewriteRule ^subfolder/(pattern)$ http://%{HTTP_HOST}/example/$1 [R=301,L]
在将脚本上载到主机web服务器之前,我使用localhost环境进行开发和测试


请告诉我,这是否可以以通用方式处理上述场景,这样我就不需要维护代码/htaccess的两个副本-一个用于本地,一个用于真实域。

最后,我找到了自己问题的解决方案。下面是如何通过仅替换输入url的所需部分将url重定向到新url的方法-在localhost和real domain上都有效

Get current directory path into a variable "BASE"

RewriteCond %{REQUEST_URI}::$1 ^(.*?/)(.*)::\2$
RewriteRule ^(.*)$ - [E=BASE:%1]

Capture the desired portion of the url and redirect there

RewriteRule ^subfolder/(pattern)$ %{ENV:BASE}$1 [R=301,L]
第一部分是将当前目录的相对路径放入变量中。这里有更多

然后在此处捕获所需的url部分“(模式)”,并在没有任何协议或域名的情况下重定向


将保留实际的协议、域名和查询字符串。所以对本地主机和真实域都很有效。

最后,我找到了自己问题的解决方案。下面是如何通过仅替换输入url的所需部分将url重定向到新url的方法-在localhost和real domain上都有效

Get current directory path into a variable "BASE"

RewriteCond %{REQUEST_URI}::$1 ^(.*?/)(.*)::\2$
RewriteRule ^(.*)$ - [E=BASE:%1]

Capture the desired portion of the url and redirect there

RewriteRule ^subfolder/(pattern)$ %{ENV:BASE}$1 [R=301,L]
第一部分是将当前目录的相对路径放入变量中。这里有更多

然后在此处捕获所需的url部分“(模式)”,并在没有任何协议或域名的情况下重定向

将保留实际的协议、域名和查询字符串。因此,它适用于本地主机和真实域

Get current directory path into a variable "BASE"

RewriteCond %{REQUEST_URI}::$1 ^(.*?/)(.*)::\2$
RewriteRule ^(.*)$ - [E=BASE:%1]

Capture the desired portion of the url and redirect there

RewriteRule ^subfolder/(pattern)$ %{ENV:BASE}$1 [R=301,L]