centos 6x nodejs express nginx https 阿里云配置

由于开发微信小程序https的需求,把阿里云上的Nodejs配置了https。

1、首先在阿里云域名管理里面申请Symantec 免费版 SSL,并验证。

2、下载密钥文件,放在程序的目录里,这里我在根目录创建https来存放。

3、在node程序里配置https,因为使用了express,所以是./bin/www文件。这里有个问题是https不能监听443端口,因为nginx需要使用这个端口,把http端口设置为8012,https端口设置为9012,代码如下:

var app = require('../app');
var debug = require('debug')('books:server');
var http = require('http');
var https = require('https');
var fs = require('fs');

var options = {
  key: fs.readFileSync('./https/domain.key'),
  cert: fs.readFileSync('./https/domain.pem'),
  requestCert: true,
  rejectUnauthorized: true
}

/**
 * Get port from environment and store in Express.
 */

var port = normalizePort(process.env.PORT || '8012');
app.set('port', 8012);

console.log('listen : ' + port);

/**
 * Create HTTPs server.
 */

//var server = http.createServer(app);
var server = http.createServer(app);
https.createServer(options, app).listen(9012);

4、配置nginx,如下:

server {
    listen  80;
    server_name domain.com www.domain.com;
    rewrite ^(.*)$  https://$host$1 permanent;
}

server {
    listen  443 ssl;
    server_name  domain.com www.domain.com;
    ssl         on;
    ssl_certificate     /etc/nginx/cert/domain.pem;
    ssl_certificate_key /etc/nginx/cert/domain.key;
    location / {
        proxy_pass http://localhost:8012;
        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 /usr/york/leeggco;
    }
}

这里要注意的地方是server_name 需要同时设置domain.com和www.domain.com这样访问domain.com的时候也会自动跳转到https。

配置完后重启nginx完成。

说点什么

avatar
  Subscribe  
提醒