title: NodeJS Express and Apache on same server
body: <p>I have a VPS with multiple virtural hosts specified in Apache config (/etc/apache2/sites-available/000-default.conf).</p>
  
  <pre><code>#Example config
  &lt;VirtualHost *:80&gt;
      ServerName example.com
      Redirect / https://example.com/
      DocumentRoot /var/www/example
      ServerAdmin admin@example.com
  &lt;/VirtualHost&gt;
  
  &lt;VirtualHost *:80&gt;
      ServerName sub.example.com
      DocumentRoot /var/www/sub.example
      ServerAdmin admin@example.com
  &lt;/VirtualHost&gt;
  </code></pre>
  
  <p>Also, I have Nodejs app on same server running with port *:3000. The problem is, that some ISP blocks that port and user can't use the app (e.g. in my school I can't access to this port). I want to that this app will run on port *:443, but I still want to use Apache to others host. Is there any way how to have app on same port as Apache and use that app only if user visit domain <a href="https://socket.example.com" rel="nofollow noreferrer">https://socket.example.com</a>, otherwise it will use Apache. I'm adding example config of my Apache server and part of nodejs app.</p>
  
  <pre><code>var fs = require('fs');
  var http = require('http');
  var https = require('https');
  var privateKey = fs.readFileSync('/etc/letsencrypt/live/socket.example.com/privkey.pem', 'utf8');
  var certificate = fs.readFileSync('/etc/letsencrypt/live/socket.example.com/cert.pem', 'utf8');
  var bodyParser = require("body-parser");
  var credentials = { key: privateKey, cert: certificate };
  var express = require('express');
  var app = express();
  var port = 3000;
  var httpsServer = https.createServer(credentials, app);
  
  
  httpsServer.listen(port, function () {
      console.log('Server running on port: ' + port);
  });
  
  
  var urlencodedParser = bodyParser.urlencoded({ extended: false });
  
  app.use(function (req, res, next) {
      res.header('Access-Control-Allow-Origin', req.headers.origin);
      res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
      res.header('Access-Control-Allow-Credentials', 'true');
      res.header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type');
  
      if ('OPTIONS' == req.method) {
          res.writeHead(200);
          res.end();
      } else {
          next();
      }
  });
  
  
  app.get('/', function (req, res) {
      res.send(400);
      console.log("visit");
  });
  </code></pre>
  
  <p>If I forgot about something just let me know and I will add it.</p>