Rando Hinn Rando Hinn - 4 months ago 37
Node.js Question

.htaccess to expressjs routes

I'm in the process of moving to a nodejs express server from apache2. In this process, I now need to convert a .htaccess to expressjs routes, but I can't figure out how to achieve this.

Here's the .htaccess file:

RewriteEngine On

#Remove .html from urls
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.html [NC,L]

# Is it a file? serve it, is it not a file? serve index.html
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.html [L]

So basically, it serves all files to the browser. And if the requested path is not a file, it serves index.html. What would these look like in expressjs routes?

Currently, routes are like this

var express = require('express');
var app = express();
var path = require('path');

app.get('*', function (req, res) {
res.sendFile('index.html',{root: path.join(__dirname, './public')});

app.listen(80, function () {
console.log('Example app listening on port 3000!');


If you are using expressjs static method with default settings then you don't need to add anything else because this rules are already applied. For more information see Serving static files in Express. Also in order to server files without the html extension you need to following middleware.

var fs = require('fs');

function(req, res, next){
  var file = path.join(path.join(__dirname, './public'), req.path + '.html';

  fs.exist(file), function(exist){
      if(!exist) return next();