如何使用.htaccess正确重定向多个URL

杰米

这是我现在在htaccess中拥有的内容:

Options +FollowSymlinks
RewriteEngine on
RewriteBase /themelink/mytheme
RewriteRule ^(.+)$  http://portal.example.com/aff.php?aff=$1&p=mytheme.php [R=301,NC]

我在/themelink/mytheme目录中有这个.htaccess文件。

这是将某人重定向http://example.com/themelink/mytheme/123456到该URLhttp://portal.example.com/aff.php?aff=123456&p=mytheme.php

这几乎是我想要做的,但是还不完全是我想要的。

我想做的是将.htaccess放在我的themelink目录中,让它可以识别URL中紧随其后的任何文件夹名称,而无需我为每个主题创建一个单独的文件夹。

例如,这是我要使用的几组链接:

http://example.com/themelink/new-theme/5643434 ---> http://portal.example.com/aff.php?aff=5643434&p=new-theme.php

http://example.com/themelink/bloggertheme/254543 ---> http://portal.example.com/aff.php?aff=254543&p=bloggertheme.php

http://example.com/themelink/test-theme/4353663 ---> http://portal.example.com/aff.php?aff=4353663&p=test-theme.php

从技术上讲,我可以为需要重定向设置的每个主题创建一个新目录,并只使用上面的.htaccess,但是我更希望有一个可以与所有主题一起使用的.htaccess。

希望这是有道理的,如果需要任何说明,请随时告诉我。

迈克尔·伯考斯基(Michael Berkowski)

如果我理解正确,则可以将.htaccess上移到/themelink目录中,并将其修改为包括两个()捕获组,第一个捕获所有捕获到第一个/遇到的捕获组,第二个捕获所有捕获到的捕获组

# .htaccess in /themelink
Options +FollowSymlinks
RewriteEngine on
# Change the RewriteBase (it actually isn't even needed)
RewriteBase /themelink
# $1 is the theme name, $2 is the aff value
RewriteRule ^([^/]+)/(.+)$  http://portal.example.com/aff.php?aff=$2&p=$1.php [R=301,NC]

该表达式([^/]+)匹配一个或多个不是a的字符,/并将其捕获为$1

现在,我注意到aff您所有示例中的值都是数字。如果是这种情况,我建议对重写进行更具体的说明以匹配那里的数字,而不是(.+)匹配任何数字。这样,无效的URL(除了数字以外的其他URL)将不会重定向,而是可以使用404进行响应。

# Ensure $2 is an integer with `\d+` (one or more digits)
RewriteRule ^([^/]+)/(\d+)$  http://portal.example.com/aff.php?aff=$2&p=$1.php [R=301,NC]

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章