正在尝试删除路径、文件扩展名以及某个查询参数(如果存在)



我对.htaccess还很陌生,但已经接近了我所需要的,但现在被卡住了。

输入:https://www.example.com/p/mypage.html

输出:https://www.example.com/mypage

这是通过以下方式实现的:

# Static pages: Remove /p from path and remove .html
RewriteRule ^p(/.*?)(?:.html)?$ $1 [R=301,L]
# All other posts just remove .html
RewriteCond %{REQUEST_URI} ^/(.+).html?$ [NC]
RewriteRule ^ /%1 [L,R=301]

然而,通常情况下,如果存在,则需要删除查询参数m=1

我需要删除上面RewriteRules中静态页面和其他帖子的查询参数。请注意,通常可能还存在其他查询参数,但我不希望删除这些参数。

示例1:

输入:https://www.example.com/p/mypage.html?param1=a&m=1&param2=b

期望输出:https://www.example.com/mypage?param1=a&param2=b

示例2:

输入:https://www.example.com/2019/12/mypage.html?param1=a&m=1&param2=b

期望输出:https://www.example.com/2019/12/mypage?param1=a&param2=b

在上述两个示例中,都删除了以下所有内容:

  • /p(如果存在(

  • .html(如果存在(

  • m=1(如果存在((有时它可能是唯一的查询参数,因此也需要考虑(

(顺便说一句,以上三个项目符号对任何将网站从Blogger/Blogspot转移到Wordpress的人都很有用,因为它们代表了路径和页面处理方式的差异(

非常感谢您对移除m=1的帮助(如果有的话(。

您可以使用此规则删除查询参数(如果存在(,也可以删除/p.html

这是您的完整信息。htaccess:

RewriteEngine On
RewriteCond %{THE_REQUEST} ?(.*&)?m=1&?(S*)sHTTP [NC]
RewriteRule ^(?:p/)?(.+)(?:.html)?$ /$1?%1%2 [R=301,NE,NC,L]
# Static pages: Remove /p from path and remove .html
RewriteRule ^p(/.*?)(?:.html)?$ $1 [R=301,L,NC,NE]
# All other posts just remove .html
RewriteRule ^(.+).html$ /$1 [L,R=301,NC,NE]

您能试一下以下内容吗。此外,请确保在测试URL之前清除浏览器缓存。

RewriteEngine ON
# Static pages: Remove /p from path and remove .html
RewriteCond %{QUERY_STRING} ^$
RewriteRule ^p(/.*?)(?:.html)?$ $1 [R=301,L]
# All other posts just remove .html
RewriteCond %{QUERY_STRING} ^$
RewriteCond %{REQUEST_URI} ^/(.+).html?$ [NC]
RewriteRule ^ %1 [L,R=301]
#Check if URI has .html with query string present in it.
RewriteCond %{THE_REQUEST} s(?:/p)?/(.*).html?(.*)(?:[&?])m=1(.*)s [NC]
RewriteRule ^ %1?%2%3 [R=301,L]


第二个解决方案:如果您只查找param1和param2参数,请尝试以下操作。

RewriteEngine ON
# Static pages: Remove /p from path and remove .html
RewriteCond %{QUERY_STRING} ^$
RewriteRule ^p(/.*?)(?:.html)?$ $1 [R=301,L]
# All other posts just remove .html
RewriteCond %{QUERY_STRING} ^$
RewriteCond %{REQUEST_URI} ^/(.+).html?$ [NC]
RewriteRule ^ %1 [L,R=301]
#Check if URI has .html with query string present in it.
RewriteCond %{THE_REQUEST} s(?:/p)?/(.*).html?(param1=[^&]*)(?:[?&])m=1(param2=[^s]*)s [NC]
RewriteRule ^ %1?%2%3 [R=301,L]

您可以使用以下规则从URL中删除m=1查询参数。

RewriteEngine on
RewriteCond %{QUERY_STRING} (.*?)&?(?:bm=1)(.*)$
RewriteRule ^ %{REQUEST_URI}?%1%2 [R,L]

最新更新