Apache服务器上的.htaccess文件中的301重定向

时间:2016-05-23 20:27:44

标签: apache .htaccess redirect mod-rewrite

我希望在Apache服务器上的.htaccess文件中添加两个301重定向

1- 一次301重定向

www.example.com/string1?fixed_text=anystringp=2

到:

www.example.com/string1?p=2

换句话说,必须从网址中删除以下内容:

fixed_text=anystring

2- 另一个301重定向

www.example.com/string1?fixed_text=anystring

到:

www.example.com/string1

换句话说,必须从网址中删除以下内容:

?fixed_text=anystring

3- 其中s tring1和anystring是可变的字母数字字符串, 字符串可能包括:

A to Z
a to z
0 to 9
/
.
-
&

string1和anystring最多可包含200个字符

并且 fixed_text是固定文本(不变文本)

我非常感谢你提前帮助解决这个问题。

帕特里克

2 个答案:

答案 0 :(得分:1)

重定向

/string1/?fixed_text=foobar

www.example.com/string1

您可以使用:

RewriteEngine on


RewriteCond %{THE_REQUEST} \?fixed_text=([^\s]+) [NC]
RewriteRule ^ %{REQUEST_URI}? [L,R=301]

或者:

RewriteEngine on


RewriteCond %{QUERY_STRING} ^fixed_text=(.+)$ [NC]
RewriteRule ^ %{REQUEST_URI}? [L,R=301]

答案 1 :(得分:1)

如果要从查询字符串的开头删除fixed_text=...,则必须使用QUERY_STRINGRewriteCond中捕获其后的部分。

RewriteCond %{QUERY_STRING} ^fixed_text=.*?(&(.*))?$
RewriteRule ^ %{REQUEST_URI}?%2 [L,R]

从不在启用301的情况下进行测试,请参阅此回答Tips for debugging .htaccess rewrite rules了解详细信息。 当一切按预期工作时,您可以将标记从R更改为R=301