首页 > 解决方案 > Gatsby netlify 重定向问题

问题描述

我正在为我的网站使用 gatsby 生成的静态站点并使用 Netlify 来托管它。我想防止从非尾随到斜杠的重定向。我们实施的一种解决方案是使用gatsby 插件来强制使用非尾随斜杠并禁用漂亮的 URL。但这会导致带有和不带有斜杠的页面返回 200。我想让我的静态站点将 301 从尾部重定向到非尾部斜杠页面。

标签: gatsbynetlify

解决方案


简短的回答:您不能使用这种方法直接从斜杠重定向到非斜杠。来自Netlify 的文档

您不能使用重定向规则来添加或删除尾部斜杠。

可能对您有用的是使用.htaccess方法,但我不确定它在 Netlify 的环境中会如何表现。像这样的东西应该工作:

#### Force HTTPS://WWW and remove trailing / from files ####
## Turn on rewrite engine
RewriteEngine on

# Remove trailing slash from non-filepath urls
RewriteCond %{REQUEST_URI} /(.+)/$
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ https://www.example.com/%1 [R=301,L]

# Include trailing slash on directory 
RewriteCond %{REQUEST_URI} !(.+)/$
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.+)$ https://www.example.com/$1/ [R=301,L]

# Force HTTPS and WWW 
RewriteCond %{HTTP_HOST} !^www\.(.*)$ [OR,NC]
RewriteCond %{https} off  
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]

.htaccess在 Gatsby 中创建,您可以简单地在静态文件夹中创建它,并且在构建过程中它将被转译/克隆到/public文件夹中,或者您可以使用gatsby-plugin-htaccess插件。


推荐阅读