【问题标题】:301 redirections in the .htaccess file, on an Apache serverApache 服务器上的 .htaccess 文件中的 301 重定向
【发布时间】:2016-09-20 20:43:39
【问题描述】:

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

1-一个 301 重定向将是:

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

到:

www.example.com/string1?p=2

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

fixed_text=anystring

2- 另一个 301 重定向是:

www.example.com/string1?fixed_text=anystring

到:

www.example.com/string1

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

?fixed_text=anystring

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

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

string1 和 anystring 最多可以有 200 个字符

其中fixed_text 是固定文本(不变文本)。

非常感谢您在此问题上提供的任何帮助。

帕特里克

【问题讨论】:

  • 为什么不直接忽略 Web 应用程序中的 fixed_text 参数?
  • 我的目标是将旧网址重定向到新网址。因此,我想使用 301 重定向。

标签: apache .htaccess redirect mod-rewrite


【解决方案1】:

如果要从查询字符串的开头去除fixed_text=...,则必须在RewriteCond 和QUERY_STRING 中捕获它之后的部分。

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

永远不要在启用301 的情况下进行测试,有关详细信息,请参阅此答案Tips for debugging .htaccess rewrite rules。 当一切正常时,您可以将标志从 R 更改为 R=301。

【讨论】:

    【解决方案2】:

    从重定向

    /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]
    

    【讨论】:

    • 非常感谢 Olaf Dietsche 和 starkeen。我添加了 Olaf 给出的解决方案,它就像一个魅力。帕特里克
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-09
    • 1970-01-01
    • 1970-01-01
    • 2015-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多