Nodejs app cant force http to https

Before i deploy the nodejs app, forcing http to https is working (tested just for index.html)…

Now i deploy nodejs app in cyberpanel, all work well, but force http to https is not working,

i already added this to vHost Conf

context / {
  type                    appserver
  location                /home/houze.homes/public_html
  binPath                 /usr/bin/node
  startupFile             server.js
  appType                 node
  maxConns                100
 
  rewrite  {
 
  }
  addDefaultCharset       off
}

i already add this to .htaccess

RewriteEngine On
RewriteCond %{HTTPS}  !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]

but its not working force http to https, why?

Welcome @afandiazmi Happy you are here

Try

# the nodejs app port consumed
RewriteCond %{SERVER_PORT} ^3000$
RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]

Thanks for the reply, but still not working

Did you check your code ? You might be bypassing secure routes

this is my server.js file


const mongoose = require('mongoose');
const dotenv = require('dotenv');

dotenv.config({ path: './config.env' });

const app = require('./app');


const port = process.env.PORT || 3000;
const server = app.listen(port, () => {
  console.log(`App running on port ${port}...`);
});

process.on('unhandledRejection', (err) => {
  console.log('UNHANDLED REJECTION! 💥 Shutting down...');
  console.log(err.name, err.message);
  server.close(() => {
    process.exit(1);
  });
});

and this is my app.js file


const path = require('path');
const express = require('express');
const helmet = require('helmet');
const xss = require('xss-clean');
const hpp = require('hpp');
const cookieParser = require('cookie-parser');
const compression = require('compression');
const myRouter = require('./routes/myRoutes');

const app = express();

app.set('view engine', 'pug');
app.set('views', path.join(__dirname, 'views'));

app.use(express.static(path.join(__dirname, 'public')));

app.use(
  helmet.contentSecurityPolicy({
    useDefaults: true,
    directives: {
      'img-src': ["'self'", 'https: data:'],
      'frame-src': ["'self'", 'https: data:'],
      defaultSrc: ["'self'", 'data:', 'blob:'],
    },
  })
);

// Development logging
if (process.env.NODE_ENV === 'development') {
 // do something here
}
// console.log(process.env.NODE_ENV);

// Limit request from same API
const limiter = rateLimit({
  windowMs: 60 * 60 * 1000, // 15 minutes
  max: 100,
  message: 'Too many request from this IP, please try again in an hour',
});
app.use('/api', limiter);

app.use(express.json({ limit: '20kb' }));
app.use(express.urlencoded({ extended: true, limit: '20kb' }));
app.use(cookieParser());
app.use(xss());
app.use(compression());

app.use('/', myRouter);
app.all('*', (req, res, next) => {
  next(new AppError(`Can't find ${req.originalUrl} on this server!`, 404));
});
app.use(globalErrorHandler);

module.exports = app;

You can use native https.createServer() function and pass ssl key and certificate in your app.js or your entry file/point

ok i will try that later, btw can i know how to change NODE_ENV to production?

var https = require("https");
app.get("/", function (req, res) {
  res.send("hello world");
});

https
  .createServer(
    {
      key: fs.readFileSync("server.key"),
      cert: fs.readFileSync("server.cert"),
    },
    app
  )
  .listen(3000, function () {
    console.log(
      "ExpressJS App is running on port 3000 using SSL"
    );
  });

You can access environment variable like this

var env = process.env.NODE_ENV
// or
app.get('env')

To set it using SSH

export NODE_ENV=production

Try this may help you How to enable Rewrite Rules (Disabled by CyberPanel)

i will try this too

thanks all for reply, now i have fix the problem by doing this,

go to https://yourdomain.com:7080, refer here for login credential, https://www.interserver.net/tips/kb/how-to-reset-the-litespeed-admin-credentials/

then go to Virtual Host, and select the my webApp

then simply edit our app server

and lastly just add this

Thanks all for you guys help

This topic was automatically closed 3 hours after the last reply. New replies are no longer allowed.