将非 www 重定向到 www 给我数百个 404

Redirect non-www to www giving me hundreds of 404's

感谢任何能花点时间看看这个的人。

最近我在我的网站上创建了一个新部分“子域”,在这个新文件夹中我安装了 Joomla CMS,url 如下所示:http://www.example.com/subdomain/

在此文件夹中,我添加了一个 htaccess 文件。

## No directory listings
# Redirect non-www to www:
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/ [R=301,L]

当我尝试访问时说 http://example.com/subdomain/anytrailingstring then it's NOT redirecting me to http://www.example.com/subdomain/anytrailingstring as I expected, it is redirecting to http://www.example.com/anytrailingstring 遗漏了 /subdomain/ 这当然是一个不存在的页面,因此是 404。

这是个问题。

我在根 .htacces 文件中没有任何指令,除了这个:

DirectoryIndex index.php
Options +FollowSymLinks
RewriteEngine on
RewriteBase /
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

有人能看出为什么子域 htaccess 没有正确重定向到吗?我错过了什么吗?

我对 htaccess 一点都不擅长,如果有人能帮助我,我将不胜感激。 谢谢!

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/ [R=301,L]

您需要使用 REQUEST_URI 服务器变量而不是反向引用 (</code>)。由 <code>RewriteRule 模式 (第一个参数)匹配的 URL 路径是相对于当前目录的,因此不包括父子目录(即 /subdomain 在你的例子中)。

改为这样做:

RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

您需要清除浏览器缓存,因为错误的(301 - 永久性)重定向已被浏览器缓存。使用 302(临时)重定向进行测试以避免潜在的缓存问题。

但是,有几个问题:

  • 为什么不使用 HTTPS? (您正在重定向到父 .htaccess 文件中的 HTTPS - 但现在这已被子目录中的 mod_rewrite 指令覆盖。)
  • 为什么不将此包含在父 .htaccess 文件中?

更新: 所以,考虑到以上几点...如果你想将此规则移动到根目录中的父 .htaccess 文件,那么就拥有它像这样:

DirectoryIndex index.php
Options +FollowSymLinks
RewriteEngine on

# Redirect non-www to www (and HTTPS)
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# Redirect HTTP to HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

指令的顺序是确保最多只有 1 个重定向(假设您没有实施 HSTS)。

您不必要地复制了 RewriteEngine 指令(所以我删除了第二个实例)。

未使用 RewriteBase 指令。

您的 HTTP 到 HTTPS 规则中的捕获子组不是必需的。 IE。在这种情况下,^ 优于 ^(.*)$


旁白:.

...a new section "subdomain" in my website and in this new folder I have includes a Joomla CMS installation the url looks like this: http://www.example.com/subdomain/

这是一个 子目录,不是“子域”。

这是一个“子域”:

http://subdomain.example.com/