在 Nginx 中创建一个 301 重定向,删除以某些 URL 路径结尾的 `.html`?

Create a 301 redirect in Nginx that removes the `.html` ending from certain URL paths?

如何在 Nginx 中创建 301 重定向以删除某些 URL 结尾的 .html

我想将所有博客 post 的 (301) 重定向到同一个 URL 但没有 .html.

例如:

www.mydomain.com/blog/post1.html -> www.mydomain.com/blog/post1 www.mydomain.com/blog/post2.html -> www.mydomain.com/blog/post2

注意:我只想从 www.mydomain.com/blog/ 中删除 html 并保留其余站点路径是。

我设法为每个 post 创建了一个重定向,但肯定有比这更好的方法:

rewrite ^/blog/post1.html$ https://www.mydomain.co.uk/blog/post1 permanent;
location ~ ^/(.*)\.html$ {
    return 301 https://$host/;
}

仅对于博客子路径,这也应该有效:

location ~ ^/blog/(.*)\.html$ {
    return 301 https://$host/blog/;
}

应该可以解决问题。

~ 表示正则表达式。

^ 和 $ 表示正则表达式的开头和结尾。

(.*) 表示捕获任意数量的未定义字符(. 表示未定义 * 表示任意数字)

and .html 表示以 .html 结尾(哇)

然后将其全部重定向到 https://$host/$1,其中 host 是通过的主机,$1 是位置正则表达式中捕获的字符串。

尝试一下,如果它在您的环境中有效,请告诉我。