首页 > 解决方案 > 如何仅使用 .htaccess 在 1and1 上托管的 WordPress 网站上的所有页面上强制使用 HTTPS

问题描述

在激活我从 1and1 托管收到的免费 SSL 证书后,我不知疲倦地尝试强制 HTTPS 访问我的整个 WordPress 网站,以便将所有过去的 HTTP 链接重定向到 HTTPS。我想通过仅修改我的 web 文件夹根目录中的 .htaccess 文件来强制使用 HTTPS。我尝试了在网上找到的多个示例,包括:

http://www.wpbeginner.com/wp-tutorials/how-to-add-ssl-and-https-in-wordpress/

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{SERVER_PORT} 80 
RewriteRule ^(.*)$ https://www.yoursite.com/$1 [R,L]
</IfModule>

https://www.1and1.com/digitalguide/hosting/technical-matters/the-ten-best-htaccess-tricks/

<IfModule mod_rewrite.c>
# activate HTTPS
RewriteEngine On
RewirteCond %{Server_Port} !=443
RewriteRule ^(.*)$ http://yourdomain.tld/$1 [R=301, L]
</IfModule>

在尝试了所有这些修改 .htaccess 文件的方法后,它们都没有奏效。我终于遇到了这个Stack Overflow 问题,并将 PHP 代码块放在我当前主题文件夹中的 functions.php 文件中。这是代码:

if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] !== 'on') {
    if(!headers_sent()) {
        header("Status: 301 Moved Permanently");
        header(sprintf(
            'Location: https://%s%s',
            $_SERVER['HTTP_HOST'],
            $_SERVER['REQUEST_URI']
        ));
        exit();
    }
}

这段 PHP 代码实现了我强制所有链接到 HTTPS 的目标。但是,我希望保持我的代码干净并将其全部保留在 .htaccess 文件中以便更好地组织,因此我不必记住每次更改 WordPress 的主题时都将 PHP 代码添加到 functions.php 文件中网站。

谁能解释如何通过仅修改 .htaccess 文件来完成强制 HTTPS 或解释我可能出错的地方?

我的 .htaccess 文件中唯一有效的代码块是:

# 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

AddHandler x-mapp-php5.5  .php

而且我已经将“WordPress 地址(URL)”和“站点地址(URL)”的 WordPress 设置更改为“ https://example.com/ ”。

标签: wordpressapache.htaccessmod-rewritehttps

解决方案


根据Apache 文档,指令可以更好地处理诸如http必须重定向到的请求等情况。该指令将进入服务器配置文件。httpsRedirect

如果您只能访问 .htaccess 那么您应该能够使用以下内容:

RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

推荐阅读