Shan Robertson
Shan Robertson

Reputation: 2742

Blocking static file access in expressJS

I'm trying to block certain files in my site from being publicly accessible. For example, if you go to mysite.com/package.json instead of displaying it in the browser i just want to send and error or redirect back to my homepage or something. I feel like this should be easy... but i haven't been able to get anything to work. there isn't anything complicated about the site, and it's running of a fairly simple server.js

var appRoot        = __dirname,
    express        = require('express'),
    chalk          = require('chalk'),
    mongoose       = require('mongoose'),
    bodyParser     = require('body-parser'),
    methodOverride = require('method-override'),
    path           = require('path'),
    errorhandler   = require('errorhandler'),
    os             = require('os'),
    http           = require('http'),
    Routes;


// -----------------------------
// Configuration
// -----------------------------
var port, env, logs;

// Switch some vars based on the ENV
if(process.env.NODE_ENV === 'production'){
  port = 3000;
  env = 'production';
} else {
  port = 8080;
  env = 'development';
}

// Express Variables
var app     = express();
var router  = express.Router();

// Use static files in root
app.use(express.static(__dirname));

// API config
app.use(bodyParser.json());
app.use(methodOverride());
app.use(errorhandler({ dumpExceptions: true, showStack: true }));

// Database
mongoose.connect(mydb);

// Routes / API Config
Routes = require(appRoot + '/routes')(app, router, mongoose);

// After all routes don't match ie. refreshing a page, send index.html
app.get('/*', function(req, res) {
  res.sendFile(__dirname + '/index-' + env + '.html');
});

app.listen(port);

I was hoping to do something like:

app.get('/package.json', function(){
 res.end('Not allowed');
});

or even before i send it the static html index check if they are trying to access a restricted file. Any suggestions, resources etc are welcomed. If you need any more info just ask.

Upvotes: 1

Views: 2216

Answers (1)

Andrey
Andrey

Reputation: 1553

Based on your comment

You should replace this line:

app.use(express.static(__dirname ));

with this:

app.use('/assets', express.static(__dirname + '/assets'));
app.use('/views', express.static(__dirname + '/views'));

Upvotes: 3

Related Questions