首页 > 网站运行/故障 > 如何使用 .HTACCESS 重定向网站文件

如何使用 .HTACCESS 重定向网站文件

作为配置文件.htaccess功能非常强大。即使是最轻微的语法错误(如缺少空格)也可能导致您的内容无法正确显示或根本无法显示。

由于.htaccess是隐藏的系统文件,请确保您的 FTP 客户端配置为显示隐藏文件。

1、创建.htaccess文件

使用记事本等文本编辑器创建一个空文本文件,保存为htaccess.txt。

将文件保存为 htaccess.txt 的原因是许多操作系统和 FTP 应用程序.htaccess默认无法读取或查看文件。上传到美国服务器后,您可以将文件重命名为.htaccess.

2. 编辑 htaccess.txt 文件的内容。下面是一些您可以使用的重定向例子。

301(永久)重定向:

使用 301 重定向 .htaccess 将整个站点永久地指向不同的 URL。这是最常见的重定向类型,在大多数情况下都很有用。在这个例子中,我们重定向到“example.com”域。

将以下内容添加到您网站的 .htaccess 文件时,请务必将 example.com 替换为您自己的域名。如你的域名开启了SSL https访问,需要在下面的域名前使用https或不是http。

# This allows you to redirect your entire website to any other domain
Redirect 301 / http://example.com/

302(临时)重定向:

将整个站点指向不同的临时 URL。当您有一个临时登录页面并计划在以后切换回主登录页面时,这对于 SEO 目的非常有用:

# This allows you to redirect your entire website to any other domain
Redirect 302 / http://example.com/

将 index.html 重定向到特定的子文件夹:

# This allows you to redirect index.html to a specific subfolder
Redirect /index.html http://example.com/newdirectory/

将旧目录重定向到新目录:

# 将example.com/old 重定向到example.com/new 
RewriteRule ^old/(.*)$ /new/$1 [R=301,NC,L]

将旧文件重定向到新文件路径:

# Redirect old file path to new file path
Redirect /olddirectory/oldfile.html http://example.com/newdirectory/newfile.html

重定向到带有 URL 掩码的子文件夹:

# Show the content in example.com/folder2, but the URL appears as example.com/folder1
RewriteEngine On
RewriteRule ^folder1/?$ /folder2/

# To show the URL as just example.com RewriteEngine On
RewriteRule ^/?$ /folder2/

重定向到特定的索引页面:

# Provide Specific Index Page (Set the default handler)
DirectoryIndex index.html

重定向错误消息:

该站点将重定向到主页,而不是提示 404 Not Found 错误页面:

# 将 404 错误页面重定向到主页
ErrorDocument 404 http://example.com/

将不存在的页面重定向到 index.php

# 将不存在的页面重定向到 index.php 
Options +SymLinksIfOwnerMatch 重写引擎开启 RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d 重写规则。/index.php [L]

3. 上传此文件至美国虚拟主机或服务器根目录下并将其重命名为.htaccess

测试是否可正常使用,如有问题,需要认真检查代码,包括查看空格、符号等错误。

发表回复