站点图标 李英杰害虫

WordPress整站开启HTTPS协议,让站内链接支持SSL证书

方法一、传统方式将WordPress开启整站HTTPS协议
1.登录和后台强制开启SSL,可以通过修改wp-config.php文件,直接在文件末尾加入以下两行代码:

define('FORCE_SSL_LOGIN', true);
define('FORCE_SSL_ADMIN', true);

或者在确认WordPress站点已经开启https协议并可以通过https访问,那么可以直接登陆后台,通过“设置”中“常规”里面把“WordPress地址(URL)”、“站点地址(URL)”两个地址的http修改为https并保存。

WordPress整站开启HTTPS协议,让站内链接支持SSL证书

2.然后还需要确定的就是通过“设置”中“多媒体”菜单把“文件的完整URL地址”也改为https协议,如果文件的完整URL地址之前是缺省的,那么也就可以不用修改。

WordPress整站开启HTTPS协议,让站内链接支持SSL证书

WordPress自定义上传路径 和 生成文件的URL地址(来源https://www.wpdaxue.com/custom-upload-dir.html

直接将下面的代码添加到主题的 functions.php,就可以恢复设置界面了

//找回上传设置
if(get_option('upload_path')=='wp-content/uploads' || get_option('upload_path')==null) {
update_option('upload_path',WP_CONTENT_DIR.'/uploads');
}

3.同时为了保证WordPress站点之前添加的各个链接或者多媒体文件把http协议改成https协议,我们还需要通过数据库SQL查询执行一条替换命令,代码如下:
update wp_posts set post_content = replace(post_content, 'http://zhangzifan.com','https://zhangzifan.com');
以上代码请按照自己数据库表名(wp_posts)和网站域名修改后在执行即可。

方法二、代码方式让WordPress开启整站HTTPS协议

我们都知道,我们如果使用了WordPress的多媒体上传和插入图片附件的时候,附件都被WordPress标记为了绝对链接,一般需要修改数据库,但这种方法子凡是非常不推荐的,对于不是非常熟悉数据库的同学们估计网站直接被毁也是可能的,所以子凡在这里推荐一种自己正在使用和即将在Fanly主题2.0支持的一种方法。

老规矩,编辑当前主题下的 functions.php 文件,加入以下代码:

代码一:HTTPS绝对链接替换
//WordPress SSL at 2016/12/29 update
add_filter('get_header', 'fanly_ssl');
function fanly_ssl(){
if( is_ssl() ){
function fanly_ssl_main ($content){
$siteurl = get_option('siteurl');
$upload_dir = wp_upload_dir();
$content = str_replace( 'http:'.strstr($siteurl, '//'), 'https:'.strstr($siteurl, '//'), $content);
$content = str_replace( 'http:'.strstr($upload_dir['baseurl'], '//'), 'https:'.strstr($upload_dir['baseurl'], '//'), $content);
return $content;
}
ob_start("fanly_ssl_main");
}
}
代码二:HTTPS相对链接替换
//WordPress SSL
add_filter('get_header', 'fanly_ssl');
function fanly_ssl(){
if( is_ssl() ){
function fanly_ssl_main ($content){
$siteurl = get_option('siteurl');
$upload_dir = wp_upload_dir();
$content = str_replace( 'http:'.strstr($siteurl, '//'), strstr($siteurl, '//'), $content);
$content = str_replace( 'http:'.strstr($upload_dir['baseurl'], '//'), strstr($upload_dir['baseurl'], '//'), $content);
return $content;
}
ob_start("fanly_ssl_main");
}
}

退出移动版