Search code examples
node.jsapache.htaccess

Configuration .htaccess file for NodeJS deployment


I want to deploy my NodeJS app on a remote Apache server, but i don't know what .htaccess configuration do i need to for the my code to work on the server, i've tried this but it doesn't work as server gives 500 Internal server error:

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f    
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/?(.*)$ https://www.johnny.group:8000/$1 [P]

index.js

import express from "express";
import cors from "cors";
const app = express();
app.use(cors());
const port = process.env.PORT || 8000;

app.use(express.json());

app.get("/", (req, res) => {
  try{
  res.send("Hello World!");
  }
  catch(err){
  res.send(err.message);
  }
});

app.listen(port, () => {
   console.log(`Server is running on port ${port}`);
});



Solution

  • Watch out those possible scenarios that might be causing an error:

    1. You need mod_proxy and mod_proxy_http for proxying requests. You can enable these modules by running the following commands on the servee

        sudo a2enmod proxy
        sudo a2enmod proxy_http
        sudo a2enmod rewrite
        sudo systemctl restart apache2

    1. The .htaccess file is intended to rewrite requests to the Node.js server running on a different port. Here's a demonstration of how you might configure it:

        RewriteEngine On
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^(.*)$ http://localhost:8000/$1 [P,L]

    1. Make sure that mod_proxy is Configured properly
    2. Ensure that your Apache server can access localhost:8000 where your Node.js app runs.
    3. After changes to .htaccess or any Apache configuration file, don't forget to restart Apache to apply the changes.