WordPress全站启用https设置

来自:互联网
时间:2020-03-21
阅读:

HTTPS无疑是要更安全点,但证书折腾也是个体力活,要用好的证书还会有不少的费用产生,当然也有免费的证书,体验盒子在2017年的时候正式启用了HTTPS,最近有人来问WordPress启用https要做哪些操作,索性就写成文章供有需要的朋友自取。

WordPress全站启用https设置

步骤

  1. 准备好https证书文件(今天不讲这个环节,改天补充);
  2. 修改Nginx配置;
  3. 修改替换站内已有http连接为https

启用https Nginx配置

##
# @server online
# @host xxx.com
# @desc nginx host rules
##
# HTTP Server
server {
    listen 80;
    server_name xxx.com www.xxx.com;
    rewrite ^ https://$server_name$request_uri permanent;
}
# HTTPS Server
server {
    listen 443;
    server_name xxx.com www.xxx.com;
    root /var/www/path;
    index index.php;
    error_log /var/log/nginx/xxx.com.log crit;
    ssl on;
    ssl_certificate /etc/nginx/ssl/xxx.com.crt;
    ssl_certificate_key /etc/nginx/ssl/xxx.com.key;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # do not use SSLv3 ref: POODLE
    
    client_max_body_size 20M;
    location / {
        try_files $uri $uri/ /index.php;
    }
    location ~ .php$ {
        fastcgi_split_path_info ^(.+.php)(/.+)$;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
    }
    location ~* .(eot|ttf|woff)$ {
        add_header Access-Control-Allow-Origin '*';
    }
    location ~/.ht {
        deny all;
    }
}

规则解释:启用443端口,指定域名及证书,并设置跨域Header权限(这一步关键,如果不设置跨域的话后边站内所有连接的http都会在console显示不安全警告)。

上面的规则中你需要把网址/程序路径/ssl证书路径改为你自己的,同时如果你有自己的其它设定也要加进去,如果没有只是单纯的WordPress程序直接使用即可,然后重启Nginx服务。

重启后这时候你在服务层已经启用了https服务了。

启用https修改站点地址及内链地址

  1. 修改wordpress后台设置中的wordpress地址及站点地址为https;
  2. 在我们主题的模板中,找到function.php中,尾部增加如下代码:
//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, '//'), '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");
    }
}

目的是将我们内链的图片等地址的http用https代替,使用上面函数并不是从数据库内彻底替换https,而是进行了转换,如果你需要彻底的转换,则需要执行下面SQL:

# 资源附件
UPDATE wp_posts SET post_content = REPLACE(post_content,'http://www.xxx.com/wp-content/uploads','https://www.xxx.com/wp-content/uploads')
# 描连接等
UPDATE wp_posts SET post_content = replace(post_content, 'http://www.xxx.com/','https://www.xxx.com/');

运行前请务必先备份数据库,连接换成你自己的。

结束,跟着步骤做完,你的WordPress启用https已经完成了。

返回顶部
顶部