Skip to content

Commit 1f28cca

Browse files
jjmerinodougwilson
authored andcommitted
Fix redirect loop when index file serving disabled
fixes #18
1 parent a0f5c95 commit 1f28cca

File tree

3 files changed

+48
-1
lines changed

3 files changed

+48
-1
lines changed

HISTORY.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
unreleased
2+
==========
3+
4+
* Fix redirect loop when index file serving disabled
5+
16
1.6.3 / 2014-09-24
27
==================
38

index.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,8 +62,9 @@ exports = module.exports = function serveStatic(root, options) {
6262
var opts = merge({}, options)
6363
var originalUrl = parseurl.original(req)
6464
var path = parseurl(req).pathname
65+
var hasTrailingSlash = originalUrl.pathname[originalUrl.pathname.length - 1] === '/'
6566

66-
if (path === '/' && originalUrl.pathname[originalUrl.pathname.length - 1] !== '/') {
67+
if (path === '/' && !hasTrailingSlash) {
6768
// make sure redirect occurs at mount
6869
path = ''
6970
}
@@ -74,6 +75,10 @@ exports = module.exports = function serveStatic(root, options) {
7475
if (redirect) {
7576
// redirect relative to originalUrl
7677
stream.on('directory', function redirect() {
78+
if (hasTrailingSlash) {
79+
return next()
80+
}
81+
7782
originalUrl.pathname += '/'
7883

7984
var target = url.format(originalUrl)

test/test.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -559,6 +559,43 @@ describe('serveStatic()', function(){
559559
});
560560
});
561561
});
562+
563+
describe('when index file serving disabled', function(){
564+
var server;
565+
before(function () {
566+
server = createServer(fixtures, {'index': false}, function (req) {
567+
// mimic express/connect mount
568+
req.originalUrl = req.url;
569+
req.url = '/' + req.url.split('/').slice(2).join('/');
570+
});
571+
});
572+
573+
it('should next() on directory', function (done) {
574+
request(server)
575+
.get('/static/users/')
576+
.expect(404, 'sorry!', done);
577+
});
578+
579+
it('should redirect to trailing slash', function (done) {
580+
request(server)
581+
.get('/static/users')
582+
.expect('Location', '/static/users/')
583+
.expect(303, done);
584+
});
585+
586+
it('should next() on mount point', function (done) {
587+
request(server)
588+
.get('/static/')
589+
.expect(404, 'sorry!', done);
590+
});
591+
592+
it('should redirect to trailing slash mount point', function (done) {
593+
request(server)
594+
.get('/static')
595+
.expect('Location', '/static/')
596+
.expect(303, done);
597+
});
598+
});
562599
});
563600

564601
function createServer(dir, opts, fn) {

0 commit comments

Comments
 (0)