如何将网站移动到子目录并进行 301 重定向?

如何将网站移动到子目录并进行 301 重定向?

我已将网站路径从根目录更改为子文件夹。例如:将 example.com 更改为 example.com/subfolder,一切正常。但现在我想将旧 URL 301 重定向到新 URL。

例如:使用 htaccess 将 example.com/how-to-play-football 重定向到 example.com/subfolder/how-to-play-football。

如果有人访问我的旧 URL,他们应该自动重定向到我的新 URL。

答案1

如果您使用 .htaccess 文件执行此操作(我从您问题的标签中猜测),它看起来会像这样(将子文件夹替换为您实际的子文件夹名称,将示例替换为您实际的站点名称):

RewriteEngine on
RewriteBase /

# Rule to NOT rewrite requests that already have the /subfolder/ in them
RewriteCond %{REQUEST_URI} !^/subfolder/

# example is the URL without the .com, so replace it with your actual domain without the top level domain
RewriteCond %{HTTP_HOST} ^(www\.)?example\.

# Rewrite all those URLs to put subfolder between the site path and the root site
RewriteRule ^(.*)$ /subfolder/$1 [L]

该文件必须放在 webroot 目录中,并且您的 web 服务器必须配置为接受 .htaccess 文件(在 apache 上,对于您网站的根目录,应为“AllowOverride All”)。但是,如果您控制着 web 服务器(nginx/apache/whatever),最好在 web 服务器级别进行配置,只有当它只是来自 web 托管商的网络空间或您无权访问 web 服务器配置时,才应采用 .htaccess 方法:

如果您有权访问 httpd 主服务器配置文件,则应完全避免使用 .htaccess 文件。使用 .htaccess 文件会降低 Apache http 服务器的速度。最好将 .htaccess 文件中包含的任何指令设置在目录块中,因为它将具有相同的效果,且性能更佳。

https://httpd.apache.org/docs/2.4/howto/htaccess.html

相关内容