Nginx 配置https

2018-11-04  本文已影响26人  夏夏夏夏顿天

Nginx 和 node https配置

1.生成证书

自制CA私钥

openssl genrsa -des3 -out ca.key 4096

自制CA证书

openssl req -new -x509 -days 3650 -key ca.key -out ca.crt

自制Server私钥,生成免密码版本

openssl genrsa -des3 -out server.key 4096 openssl rsa -in server.key -out server.nosecret.key

制作csr文件

openssl req -new -key server.key -out server.csr

用CA证书私钥对csr签名(CA不能用X509,这点需要注意)生成Server证书

openssl ca -days 3650 -in server.csr -cert ca.crt -keyfile ca.key -out server.crt

2.创建node服务端

安装node环境,新建demo文件夹。打开终端输入命令:

npm init

npm install express

新建serve.js编写以下代码:

var app = require('express')();
var fs = require('fs');
var http = require('http');
var https = require('https');
var privateKey  = fs.readFileSync('private.pem', 'utf8');
var certificate = fs.readFileSync('file.crt', 'utf8');
var credentials = {key: privateKey, cert: certificate};

var httpServer = http.createServer(app);
var httpsServer = https.createServer(credentials, app);
var PORT = 18080;
var SSLPORT = 18081;

httpServer.listen(PORT, function() {
    console.log('HTTP Server is running on: http://localhost:%s', PORT);
});
httpsServer.listen(SSLPORT, function() {
    console.log('HTTPS Server is running on: https://localhost:%s', SSLPORT);
});

// Welcome
app.get('/', function(req, res) {
    if(req.protocol === 'https') {

终端运行开启服务:

node serve.js

3.添加ngnix服务

安装nginx,修改Nginx.cfg文件。

server {
    listen 443;
    server_name localhost;
    ssl on;
    ssl_certificate ssl/server.crt;
    ssl_certificate_key ssl/server.nosecret.key;
    location /t {
        echo "Hello World";
    }
}

4.配置服务转发

配置转发实现http和https共同访问

server {  
    listen  80;  
    server_name blog.90its.cn;   
    rewrite ^(.*)$  https://$host$1 permanent;  
}
server {
    listen  443 ssl;
    server_name  www.wishpeng.top;
    ssl         on; 
    ssl_certificate     /home/admin/https/file.crt; 
    ssl_certificate_key /home/admin/https/private.pem; 
    location / {
        proxy_pass http://localhost:18080;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
    location /public {
        root /phpstudy/wishpeng;
    }
}

小礼物走一走,来简书关注我

作者:WishPeng
链接:https://www.jianshu.com/p/7c865905b9f4
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

上一篇下一篇

猜你喜欢

热点阅读