簡體   English   中英

將Express.js HTTP重定向到同一端口上的HTTPS

[英]Redirect Express.js HTTP to HTTPS on the same port

在開發過程中,我想啟動使用http和https模塊的server.js(app.js)腳本的兩個實例,將路由重定向( * )轉換為https並在一個實例的3000端口運行,另一個在該端口運行3001 現在,如果我將端口80為端口443 ,則沒有任何問題,除了我必須使用sudo啟動腳本並且我只能有一個實例。 有沒有一種方法可以使http可以重定向到同一端口上的https。

application.get('*', function(request, response, next) {
    if (!request.secure) {
        response.redirect('https://' + request.headers.host + request.url);
    } else {
        next();
    }
});

http
    .createServer(application)
    .listen(80, function() {
        var uid = parseInt(process.env.SUDO_UID);
        if (uid) {
            process.setuid(uid);
        }
    });
https
    .createServer({
        key: fs.readFileSync(...),
        cert: fs.readFileSync(...)
    }, application)
    .listen(443, function() {
        var uid = parseInt(process.env.SUDO_UID);
        if (uid) {
            process.setuid(uid);
        }
        console.log(
            'Express server running in %s environment at %s',
            process.env.NODE_ENV || 'development',
            moment()
        );
    });

只需將端口保留在ENV變量中,然后使用它來偵聽和重定向方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM