Skip to content

Instantly share code, notes, and snippets.

@eugeniy
Created September 5, 2011 22:38
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eugeniy/1196080 to your computer and use it in GitHub Desktop.
Save eugeniy/1196080 to your computer and use it in GitHub Desktop.
Redirect domains starting with www to non-www ones in node.js, express and coffeescript
express = require 'express'
app = module.exports = express.createServer()
# redirect to a non-www domain
app.get '/*', (req, res, next) ->
if req.headers.host.match(/^www\./)?
res.redirect 'http://' + req.headers.host[4..] + req.url, 301
else next()
app.get '/', (req, res) ->
res.send 'Hello World'
app.listen(process.env.PORT || 3000)
console.log "Listening on port %d in %s mode...", app.address().port, app.settings.env
@blakmatrix
Copy link

I like this better:

app.get '/*', (req, res, next) ->
if req.headers.host.match(/^www\./)?
  res.redirect "http://#{req.headers.host[4..]}#{req.url}", 301
else next()

@blakmatrix
Copy link

Thanks for updating it!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment