.htaccess - 尽管每个子目录都有自己的文件,但从根 .htaccess 文件强制规则?

.htaccess - Force rule from root .htaccess file despite each subdirectory having own file?

问题

我有 a piece of code from another Q&A 这是强制在网址中加入 www 的通用解决方案:

# Force www.
RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/ [L,R=301]

我对逻辑的理解:

If the HTTP_HOST is defined solely as "(no period string).(no period string)", ie. example.com, then capture the remainder and rebuild the URL with www affixed to the head of the HTTP_POST and captured string.

我已将此代码放在我的 Web 文档根目录下的 .htaccess 文件中。该文件夹中有许多子目录,每个子目录都包含自己的 .htaccess 文件,用于处理 automatically managed by a CMS 的重定向和清理 url。这些子目录中的所有条目都倾向于遵循以下模式:

RewriteRule ^$ /reason/displayers/generate_page.php?site_id=11111&page_id=222222
RewriteRule ^page$ /subdirectory/page/ [R=permanent]
RewriteRule ^page/$ /reason/displayers/generate_page.php?site_id=111111&page_id=333333

我遇到的第一个问题是解决方案中的RewriteRule只触发网站的根页面,而不是任何子目录或页面:

Looking at another Q&A,用户建议将RewriteOptions inherit添加到子目录.htaccess。在单个测试目录中使用我的初始 RewriteRule 执行此操作会导致以下结果:

页面内容确实出现了,但是URL肯定不如人意。该问答的 OP 留下了一条评论,指出他们需要使用 %{REQUEST_URI} 而不是试图捕获和重用它。将其用于 RewriteRule,我得到:

关闭,但为了 SEO,我当然不希望参数出现在那里。


问题

有什么方法可以将这种规则应用于所有子目录和页面,而无需进入并向每个子目录.htaccess 添加 RewriteOptions inherit 行?鉴于每次创建站点时 CMS 都会动态创建这些内容,因此手动管理该行的包含并不理想。

假设,考虑到 CMS 自动放入子目录的内容,是否有任何解决方案可以解决我尝试使用 RewriteOptions inherit 时收到的 "bad" URL? =24=]


备选

最后一个可能不在本网站的范围内,但考虑到它是相关的,我将其包括在内以防前面的内容不可行或者以下内容更可取:

是否可以使用 VirtualHosts 条目处理这种重定向?据我所知,"example.com" 和 "www.example.com" 都解析为相同的 IP 和文档根目录。如果它们可以分开,www.example.com 可以保持原样,而 example.com 设置到其他地方,允许发生明确的重定向,也许?

<VirtualHost 111.11.11.111:80>
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/html/
    ...
</VirtualHost>

确实如此,要将您的规则应用于所有 sub-directories,请在 <VirtualHost..> 部分插入此规则:

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