I've got greenlock express running well in node.js on my Windows server. However, I've added some more IP addresses to the server and find that node.js and greenlock are listening to port 443 on 0.0.0.0, thereby tieing up all the IP addresses.
How do I tell greenlock to listen to port 443 only on one specific IP address?
Is there any configuration value that I can add to this?
var greenlock = require('greenlock-express')
.init({
packageRoot: __dirname,
maintainerEmail: "....",
configDir: './greenlock.d',
cluster: false
});
That's in the examples folder https://git.rootprojects.org/root/greenlock-express.js/src/branch/master/examples/https/server.js
That's the folder you need to be looking at for more advanced uses.
"use strict";
// The WRONG way:
//var https = require('https');
//var httpsServer = https.createServer(tlsOptions, app);
//
// Why is that wrong?
// Greenlock needs to change some low-level http and https options.
// Use glx.httpsServer(tlsOptions, app) instead.
//require("greenlock-express")
require("../../")
.init({
packageRoot: __dirname,
configDir: "./greenlock.d",
maintainerEmail: "jon#example.com",
cluster: false
})
.ready(httpsWorker);
function httpsWorker(glx) {
//
// HTTPS 1.1 is the default
// (HTTP2 would be the default but... https://github.com/expressjs/express/issues/3388)
//
// Get the raw https server:
var httpsServer = glx.httpsServer(null, function(req, res) {
res.end("Hello, Encrypted World!");
});
httpsServer.listen(443, "0.0.0.0", function() {
console.info("Listening on ", httpsServer.address());
});
// Note:
// You must ALSO listen on port 80 for ACME HTTP-01 Challenges
// (the ACME and http->https middleware are loaded by glx.httpServer)
var httpServer = glx.httpServer();
httpServer.listen(80, "0.0.0.0", function() {
console.info("Listening on ", httpServer.address());
});
}
I saw that you left an issue (yesterday?), but I forgot to respond.
Related
Could not connect to localhost:3000
17:02:53
Error: Unexpected server response: 404
Handshake Details
Request URL: http://localhost:3000/socket.io/?EIO=3&transport=websocket
Request Method: GET
Status Code: 404 Not Found
My express server listen on 3000 port and socketio http on 443 port, i am able to connect socket by hosting this on ec2 instance and using ec2 ip with port number on postman socket connection ui, but on localhost connection always failed with above error on postman socket beta ui.
You need to call listen only once. If you pass your http/https server to express, app.listen() is enough. (except you want to listen on 2 different ports.. For testing, let's call it only once.)
For accessing it on localhost try setting it explicitly with the parameter hostname in app.listen().
Example:
async function startServer() {
const app = express();
const credentials = {key: key, cert: crt};
const httpsServer = createServer(credentials,app);
const io = socketIO(httpsServer);
await require('./loaders').default({ expressApp: app, socketIO: io });
// Let's only call listen once for testing purposes. If you call
// listen on the express app, your https server will automatically listen
// to the same configuration.
// httpsServer.listen(4000);
const port = 3000
const hostname = 'localhost'
// explicitly let the app listen on localhost. If hostname is not
// provided, it will take the first found ipv4 interface
app.listen(port, hostname, err => {
if (err) {
Logger.error(err);
process.exit(1);
return;
}
Logger.info(`
################################################
🛡️ Server listening on https://${hostname}:${port} 🛡️
################################################
`);
});
}
Now you should be able to connect your socket. If it still does not work try
to use http module instead of https for better isolating your problem.
Note that your server now only will be accessible using localhost and not over ip. Both may only be possible when running 2 server instances with different hostnames.
async function startServer() {
const app = express();
const credentials = {key: key, cert: crt};
const httpsServer = createServer(credentials,app);
const io = socketIO(httpsServer);
await require('./loaders').default({ expressApp: app, socketIO: io });
httpsServer.listen(443);
app.listen(config.port, err => {
if (err) {
Logger.error(err);
process.exit(1);
return;
}
Logger.info(`
################################################
🛡️ Server listening on port: ${config.port} 🛡️
################################################
`);
});
}
This is my app.ts file, I am using Ubuntu. so 443 port is not allowed, i changed this port to 4000, now the app listen on the 3000 and socket http server on 4000, but socketio not able to connect with socket url localhost:3000
I have a node server with express on top. Godaddy is the domain registrar that I use.
If I try to connect with www.example.com doesn't work, only with https://www.example.com.
This is how the code looks like:
app.use(express_enforces_ssl());
app.enable('trust proxy');
app.use (function (req, res, next) {
if(req.secure){
next();
}else {
res.redirect('https://' + req.headers.host + req.url);
}
});
var options = {
ca: fs.readFileSync('./gd_bundle-g2-g1.crt'),
key: fs.readFileSync('./server_cert_key.key'),
cert: fs.readFileSync('./cfbe0f99da37dcae.crt')
};
https = require('https').createServer(options, app);
io = require('socket.io')(https);
However, if I 'ping www.example.com' the server is reached, but not in the browser.
The process is running on port 443 (dedicated port for secured connection).
I have made port forwarding from internal port 443 with output on port 80, this is how domain registrar works, only with port 80.
I don't know how can I fix it. Do you have any idea ?
DNS doesn't usually require ports info. Browser automatically assumes 80 for http scheme and 443 for https scheme.
The app code is only listening on 443. You need to add additional:
require('http').createServer(app).listen(80);
Try normalizing the port before listen to it.
In the code below, the port will be normalized according to the app settings. If none were found, it will be defaulted to port 80
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) return val;
if (port >= 0) return port;
return false;
}
//port 443 if https:// is detected
var port = normalizePort(process.env.PORT || '80');
// for me, I imported ('http') instead of ('https')
// but it also works on port 443
https.listen(port, function listening() {
console.log('Listening on %d', server.address().port);
});
I've setup a simple HTTPS server to handle the following to situations:
Requests to https://localhost:5000/ that have a matching file in my directory are served via connect.static(__dirname). This works great for everything like my index.html and my CSS files and is working exactly as I need.
Requests to https://localhost:5000/api should redirect to https://subdomain.mydomain.com:443/api.
The proxy is properly transferring everything over HTTPS and the SSL handshake part seems to be working exactly as I would expect. The problem is that my API uses the subdomain to determine what database to connect to and what data to return. So, my API sees the request
https://localhost:5000/api/something
instead of
https://subdomain.mydomain.com/api/something
and is throwing an error telling me I have to supply the subdomain.
How can I tell the node proxy to forward (or use) the domain/subdomain when doing the proxy?
Here is my code:
var fs = require('fs');
var connect = require('connect'),
https = require('https'),
httpProxy = require('http-proxy'),
options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
},
endpoint = {
host: 'subdomain.mydomain.com',
port: 443,
prefix: '/api',
target: { https: true }
};
var proxy = new httpProxy.RoutingProxy();
var app = connect()
.use(connect.logger('dev'))
.use(function(req, res, next) {
if (req.url.indexOf(endpoint.prefix) === 0) {
proxy.proxyRequest(req, res, endpoint);
} else {
next();
}
})
.use(connect.static(__dirname));
https.createServer(options, app).listen(5000);
console.log('Listening on port 5000');
Just in case someone bumps into this old question, you should use http-proxy's changeOrigin option.
I have a Node.js Express 3.0 application which listens on port 3000 locally and 80 online, that's fine. What I need to do now however is introduce an SSL certificate.
I've looked at many sources online however they're all dated, or only work on port 443 or nothing. What I need to do however is listen on both 443 and 80 and re-direct any requests to 80 back to 443.
Are they any up to date examples of this?
I would do this with 2 distinct processes: an insecure proxy server and a secure server.
The insecure proxy listens on port 80 and responds to all requests with a 302 redirect to the secure server
Insecure Proxy
var http = require('http')
var port = 80
var server = http.createServer(function (req, res) {
// change this to your secure sever url
var redirectURL = 'https://www.google.com'
res.writeHead(302, {
Location: redirectURL
});
res.end();
}).listen(port, function () {
console.log('insecure proxy listening on port: ' + port)
})
Secure Server
var https = require('https')
var express = require('express')
var fs = require('fs')
var keyFilePath = '/path/to/key.pem'
var certFilePath = '/path/to/cert.pem'
var app = express()
// put your express app config here
// app.use(...) etc.
var port = 443 // standard https port
var options = {
key: fs.readFileSync(keyFilePath, 'utf8'),
cert: fs.readFileSync(certFilePath, 'utf8')
}
var server = https.createServer(options, app)
server.listen(port, function () {
console.log('secure server listening on port: ' + port)
})
Note that you could run both of these servers within a single process but it is more maintainable to separate the concerns into distinct processes.
I want to do a simple node.js reverse proxy to host multiple Node.JS applications along with my apache server on the same port 80. So I found this example here
var http = require('http')
, httpProxy = require('http-proxy');
httpProxy.createServer({
hostnameOnly: true,
router: {
'www.my-domain.com': '127.0.0.1:3001',
'www.my-other-domain.de' : '127.0.0.1:3002'
}
}).listen(80);
The problem is that I want to have for example app1.my-domain.com pointing to localhost:3001, app2.my-domain.com pointing to localhost:3002, and all other go to port 3000 for example, where my apache server will be running. I couldn't find anything in the documentation on how to have a "default" route.
Any ideas?
EDIT I want to do that because I have a lot of domains/subdomains handled by my apache server and I don't want to have to modify this routing table each time I have want to add a new subdomain.
For nearly a year, I had successfully used the accepted answer to have a default host, but there's a much simpler way now that node-http-proxy allows for RegEx in the host table.
var httpProxy = require('http-proxy');
var options = {
// this list is processed from top to bottom, so '.*' will go to
// '127.0.0.1:3000' if the Host header hasn't previously matched
router : {
'example.com': '127.0.0.1:3001',
'sample.com': '127.0.0.1:3002',
'^.*\.sample\.com': '127.0.0.1:3002',
'.*': '127.0.0.1:3000'
}
};
// bind to port 80 on the specified IP address
httpProxy.createServer(options).listen(80, '12.23.34.45');
The requires that you do NOT have hostnameOnly set to true, otherwise the RegEx would not be processed.
This isn't baked into node-http-proxy, but it's simple to code:
var httpProxy = require('http-proxy'),
http = require('http'),
addresses;
// routing hash
addresses = {
'localhost:8000': {
host: 'localhost',
port: 8081
},
'local.dev:8000': {
host: 'localhost',
port: 8082
},
'default': {
host: 'xkcd.com',
port: 80
}
};
// create servers on localhost on ports specified by param
function createLocalServer(ports) {
ports.forEach(function(port) {
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('<h1>Hello from ' + port + '</h1');
}).listen(port);
});
console.log('Servers up on ports ' + ports.join(',') + '.');
}
createLocalServer([8081, 8082]);
console.log('======================================\nRouting table:\n---');
Object.keys(addresses).forEach(function(from) {
console.log(from + ' ==> ' + addresses[from].host + ':' + addresses[from].port);
});
httpProxy.createServer(function (req, res, proxy) {
var target;
// if the host is defined in the routing hash proxy to it
// else proxy to default host
target = (addresses[req.headers.host]) ? addresses[req.headers.host] : addresses.default;
proxy.proxyRequest(req, res, target);
}).listen(8000);
If you visit localhost on port 8000 it will proxy to localhost port 8081.
If you visit 127.0.0.1 on port 8000 (which is not defined in our routing hash) it will go to the default 'location', namely xkcd.com on port 80.