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

Trying to remove path, file extension and, if present, a certain query parameter

我是 .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)?$  [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

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

(顺便说一句,以上三个要点对于将网站从 Blogger/Blogspot 迁移到 Wordpress 的任何人都非常有用,因为它们代表了路径和页面处理方式的差异)

非常感谢任何帮助删除 m=1(如果存在)。

能否请您尝试按照所示示例编写。另外,请确保在测试您的 URL 之前清除浏览器缓存。

RewriteEngine ON
# Static pages: Remove /p from path and remove .html
RewriteCond %{QUERY_STRING} ^$
RewriteRule ^p(/.*?)(?:\.html)?$  [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)?$  [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]

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

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

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

这是您的完整 .htaccess:

RewriteEngine On

RewriteCond %{THE_REQUEST} \?(.*&)?m=1&?(\S*)\sHTTP [NC]
RewriteRule ^(?:p/)?(.+)(?:\.html)?$ /?%1%2 [R=301,NE,NC,L]

# Static pages: Remove /p from path and remove .html
RewriteRule ^p(/.*?)(?:\.html)?$  [R=301,L,NC,NE]

# All other posts just remove .html
RewriteRule ^(.+)\.html$ / [L,R=301,NC,NE]