作为一名新手小白,分享自己解决nginx配置免费https的方法,解决cors请求失败
1、安装Nginx(ubuntu)
sudo apt-get install nginx
2、生成SSL证书
1.使用let’s encrypt颁发的免费SSL证书,安装软件
sudo apt-get update
sudo apt-get install software-properties-common
sudo add-apt-repository ppa:certbot/certbot
sudo apt-get update
sudo apt-get install python-certbot-nginx
2.生成SSL证书
certbot --nginx certonly
SSL证书生成的目录/etc/letsencrypt/live/webrtc.olcms.com/,下面会有四个证书(cert.pem,chain.pem,fullchain.pem,privkey.pem)其中webrtc.olcms.com为自己的服务器域名
3、修改配置文件/etc/nginx/sites-available/default
添加如下配置
upstream rtc{
server 127.0.0.1:9001;#你的程序端口
}
server {
listen 443;
server_name cnki.545645.cn;#你的域名
ssl on;
ssl_certificate /etc/letsencrypt/live/cnki.385073012.cn/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/cnki.385073012.cn/privkey.pem;
ssl_session_timeout 5m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2; #按照这个协议配置
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;#按照这个套件配置
ssl_prefer_server_ciphers on;
location / {
proxy_pass https://rtc;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 5;
}
}
4、解决CORS请求未成功![](https://i-blog.csdnimg.cn/blog_migrate/27d4b388b7dd94bd44d4615f17e8f2b9.png)
server {
listen 443;
server_name cnki.385073012.cn;#你的域名
ssl on;
ssl_certificate /etc/letsencrypt/live/cnki.385073012.cn/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/cnki.385073012.cn/privkey.pem;
ssl_session_timeout 5m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2; #按照这个协议配置
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;#按照这个套件配置
ssl_prefer_server_ciphers on;
location / {
proxy_pass https://rtc;
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Origin' $http_origin;
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,web-token,app-token,Authorization,Accept,Origin,Keep-Alive,User-Agent,X-Mx-ReqToken,X-Data-Type,X-Auth-Token,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 5;
}
}