在具有不同域的子文件夹上强制使用 HTTPS 和 NON-WWW 会错误地重写

Forcing HTTPS & NON-WWW on a subfolder with a different domain rewrites incorrectly

我已经在 /home/USER/public_html/ 上安装了一个 Wordpress 网站,文件夹中的 .htaccess 看起来像:

# BEGIN Redirect Alias Site to Specific Folder
    RewriteCond %{HTTP_HOST} customwebsite.com$ [NC]
    RewriteRule ^(.*)$ /customwebsite/ [L]
# END Redirect Alias Site to Specific Folder

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

上面 .htaccess 文件中的重定向别名规则允许我路由我的别名域以使用不同的文件夹,从而允许多个网站 运行 来自同一个 cPanel 帐户。

在文件夹 /home/USER/public_html/customdomain/ 中,我将 .htaccess 规则设置为:

# BEGIN WordPress
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /customdomain/
    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /customdomain/index.php [L]
</IfModule>
# END WordPress

它工作得很好;但是,如果我尝试使用我可以在互联网上找到的每组规则强制 HTTPS 和非 WWW...例如:

<IfModule mod_rewrite.c>
    # Force HTTPS & NON-WWW
    RewriteEngine On
    RewriteCond %{HTTPS} !=on  [OR]
    RewriteCond %{HTTP_HOST} !^customdomain\.com$ [NC]
    RewriteRule ^ https://customdomain.com%{REQUEST_URI} [R=301,L]
</IfModule>

以及我可以自己制作的东西,然后尝试加载以下任何内容:

他们都重定向到:

部分正确,部分错误。它不应该在域的末尾包含导致问题的文件夹,因为 URL 现在不正确。

当然,如果我删除 %{REQUEST_URI} 它可以解决重定向问题,但是如果我使用的是 Wordpress,例如每个 URL 都会出错,并且会抛出 404 页面未找到。

如何修复强制 HTTPS 和非 WWW 以允许这种情况?

您可以使用此规则 作为您在 /customdomain/.htaccess 中的第一条规则:

RewriteEngine On
RewriteBase /customdomain/

# Force HTTPS & NON-WWW
RewriteCond %{HTTPS} !=on  [OR]
RewriteCond %{HTTP_HOST} !^customdomain\.com$ [NC]
RewriteRule .* https://customdomain.com/[=10=] [R=301,L,NE]

RewriteRule ^index\.php$ - [L,NC]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L]

确保清除浏览器缓存或使用新浏览器进行测试。