前段时间在做小程序项目这边记录下遇到的问题,为了能够让小程序在预览手机时能访问到自己的API,是需要将项目从http升级为https,微信官方是这样要求的:
如果不升级的话那么使用预览到手机上,是没办法访问到接口会出现以下错误:
http升级https前提
- 拥有自己的域名并且是备案过
- 拥有SSL证书,证书可以去阿里那边免费申请(每个号限领取20次)
证书具体领取步骤如下:
到这里进行付款就可以了,购买之后就可以在阿里中看到证书了。购买完之后就需要进行配置证书信息,将证书关联到域名。
这里我附上已经签发的证书,如果是还没配置的那么将在未签发中,签发在配置完信息之后大概10分钟证书就可以下来了。
使用nginx配置https
我服务器是lnmp环境(如果服务器也没部署的话,可以看下我的lnmp搭建文章),所以下载对应的证书(nginx),压缩包里包含两个文件.key和.pem。将这两个文件放在服务器上,nginx的配置代码如下:
server{
listen 443 ssl;
server_name chayuan.vswxx.top; #绑定证书的域名
ssl_certificate /etc/nginx/ssl/3673672_chayuan.vswxx.top.pem; #证书.pen位置
ssl_certificate_key /etc/nginx/ssl/3673672_chayuan.vswxx.top.key; #证书.key位置
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
# ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
# ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
index index.html index.php;
root /home/public/cy_chayuan_php; #项目位置
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
#访问路径的文件不存在则重写URL转交给ThinkPHP处理
#!-e用来判断是否存在文件或目录
if (!-e $request_filename){
rewrite ^(.*)$ /index.php?s=$1 last;
break;
}
try_files $uri $uri/ /index.php?$query_string;
}
error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ .php$ {
# proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
location ~ .php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
location ~ /.ht {
deny all;
}
}
配置完后在Linux上运行命令检查是否有错误
cd /sbin //进入目录
./nginx -t //检测
正常情况显示:
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
完成之后重启nginx、使用https正常访问网址,如果访问不到那么就需要查看下443端口是否开启。
微信公众平台配置小程序
在可以正常使用https访问到接口的提前下,还需要去微信公众平台配置小程序服务器信息。
配置完服务器信息之后小程序也可以正常访问到数据了,到这里小程序上线访问接口就已经正常了。