.htaccess 将所有子目录重定向到新位置


.htaccess redirect all subdirectories to new location

我有用户从不同的来源(论坛、博客......)访问我的网站,链接不再存在,因此出现了 404 错误。根据他们在我的网站上访问的链接,我知道将他们发送到哪里。所以链接是这样的:

www.test.com/shop/customers/individuals/343a/?shopc=variable
www.test.com/shop/customers/company/445a/?shopc=variable
www.test.com/shop/b2b/discount/43b/?shopc=variable
...

等等

如您所见,所有链接都有 www.test.com/shop/和变量 shopc .我想做的是重定向到正确的位置。让我给你一个 2 个用户访问我的网站的例子以及我想做什么。因此,用户使用以下网址进入我的网站:

www.test.com/shop/low/index.php?shopc=variable
www.test.com/shop/company/b2b/index.php?shopc=variable

现在显示404错误,因为文件和目录

/hsphere/local/home/danuser/test.com/shop/low/index.php
/hsphere/local/home/danuser/test.com/shop/company/b2b/index.php

不再存在于我的网站上。但是基于 shopc 变量,我知道将它们重定向到哪里。

所以问题是:我可以创建一个 .htaccess 文件来重定向链接吗?

www.test.com/shop/company/b2b/user/index.php?shopc=variable

www.test.com/shop/index.php?shopc=variable

所以我可以抓住 shopc 变量并将它们重定向到正确的位置?

商店目录的 .htaccess 文件中:

RewriteEngine On
RewriteBase /shop
RewriteRule ^.*$ index.php [L,QSA]

标志QSA自动将查询字符串追加到替换请求。这就是"shopc"的传递方式。有关详细信息,请参阅 Apache mod_write 在线文档。


当我转到此 URL 时:

http://localhost/shop/company/b2b/user/index.php?shopc=variable

。我从我的/shop/index.php 文件中的print_r($_GET)获得此输出:

Array
(
    [shopc] => variable
)

我花了一些时间才找到你问题的答案。问题是查询字符串与mod_rewrite正则表达式不匹配。

应该解决您的问题的代码如下:

RewriteEngine On
RewriteCond %{QUERY_STRING} shopc=('w+)
RewriteRule ^('w+/)*$ index.php [L]

它使用RewriteCond来检查您的变量shopc是否已设置。

这就是为什么我的第一条规则不起作用,以及为什么在重写规则中转义 ? 字符不是您问题的解决方案。

#RewriteRule ^(/'w)+/?shopc=('w+)$ index.php?shopc=$2 [NC,L]

无论如何,如果您可以访问httpd配置,我建议您不要使用.htaccess,因为与propper服务器配置相比,.htaccess很慢。因为使用.htaccess,Web服务器必须在每个目录中查找.htaccess文件。