301将整个站点重定向到除index.html登录页面之外的新目录

时间:2013-06-13 22:57:25

标签: .htaccess redirect http-status-code-301

我正在处理的wordpress网站被移动到一个子目录中,因此来自其他网站的所有链接都不再起作用。我使用.htaccess实现了301重定向,这很好,因为它修复了这个问题但旧的根目录现在有一个index.html,它有我的客户绝对想要看到的着陆页。

那么,如何设置我的.htaccess以将所有流量重定向到子目录(以修复传入链接)除了根目录中的index.html,因为它具有登录页面。

我不知道htaccess如何运作良好,但这就是我现在所拥有的。

Order deny,allow
ErrorDocument 404 /404.php
DirectoryIndex index.php index.html

RewriteEngine On
RewriteCond %{REQUEST_URI} !^/$ [OR]
RewriteRule ^.*$ http://example.com/portal/$0 [R=301,L]

谢谢!

编辑以澄清: 现在,一切都从根目录重定向到子目录。我希望所有内容都重定向,除了根目录中的index.html。如果用户仅请求域名(http://example.com)而未指定页面,我还希望他/她在根目录中的index.html页面上提供服务。

1 个答案:

答案 0 :(得分:1)

以下代码执行您要求的内容:“如果请求与index.phpindex.html或”/“(即没有)匹配(并且匹配不区分大小写),则提供备用位置“

Order deny,allow
ErrorDocument 404 /404.php
DirectoryIndex index.php index.html

RewriteEngine On
RewriteCond %{REQUEST_URI} !^/index\.(php|html) [NC]
RewriteCond %{REQUEST_URI} !^/$ {NC]
RewriteRule ^.*$ http://example.com/portal/$0 [R=301,L]

我使用优秀的在线测试工具http://htaccess.madewithlove.be

对此进行了测试

使用以下测试用例:

http://example.com                -- no rewrite, second condition not met
http://example.com/               -- ditto
http://example.com/index.html     -- first condition not met
http://example.com/index.php      -- first condition not met
http://example.com/some/page.html -- rewritten as http://example.com/portal/some/page.html

编辑你说这仍然没有达到预期的效果;所以我带出了大枪。通过打开重写引擎使用指令执行的所有操作的“最大日志记录”

RewriteLog "/var/log/apache2/rewrite.log"
RewriteLogLevel 9

(显然选择你想要的任何路径),然后在终端窗口中查看日志文件的末尾

tail -f /var/log/apache2/rewrite.log

您可以快速查看哪些内容无法正常运行。有点摆弄让我看到以下代码。它表示“如果请求的URI只是/index.html/index.php,或者它是以/portal开头,或者是否为空,则不要重定向。

RewriteEngine on
RewriteCond %{REQUEST_URI} !^/index\.(php|html) [NC]
RewriteCond %{REQUEST_URI} !^/portal.*$ [NC]
RewriteCond %{REQUEST_URI} !^/$ [NC]
RewriteRule ^(.*)$ http://example.com/portal$0 [R=301,L]

测试用例对我有用 - 看看它们是否适合你!

注意:我在httpd.conf文件中进行了这些更改,而不是在根目录的.htaccess文件中。您需要小心这样才能读取根目录中的.htaccess文件 - 默认的Apache配置对该目录有Override none,因此需要一些额外的工作。通过将此配置更改放在httpd.conf文件中(并发出sudo apachectl restart命令),您可以避免这种困难。根据您托管网站的人员以及您拥有的控件,这可能不适合您。可能有一点可以在superuser.com找到这个问题的专家而不是SO ......但是我希望这对你来说很有用。

相关问题