Redirect non-www to www with Node.js and Express

|▌冷眼眸甩不掉的悲伤 提交于 2021-02-06 03:00:50

问题


I am serving a static directory like so:

var app = express.createServer();
app.configure(function(){
    app.use(express.static(__dirname + '/public'));
});

So I am not using routes at all. I would like to redirect example.com to www.example.com, is this possible using Express?


回答1:


Yes. This should do it.

var express = require("express");
var app = express.createServer();
var port = 9090;
app.all(/.*/, function(req, res, next) {
  var host = req.header("host");
  if (host.match(/^www\..*/i)) {
    next();
  } else {
    res.redirect(301, "http://www." + host);
  }
});
app.use(express.static(__dirname + "/public"));
app.listen(port);



回答2:


Alternatively, you can use a ready-made module for Express that does exactly what you want, e.g. node-force-domain.

See https://github.com/goloroden/node-force-domain for details.




回答3:


The following code preserve path while redirecting

Ex: http://foo.com/foo to http://www.foo.com/foo

    var app = express.createServer();
    self.app.all(/.*/, function(req, res, next) {
      var host = req.header("host");
      if (host.match(/^www\..*/i)) {
        next();
      } else {
        res.redirect(301, "http://www." + host + req.url);
      }
    });
    app.use('/',express.static('public'));



回答4:


You can use express-force-domain package from npm:

//install
npm install express-force-domain

///app.js
app.all('*', require('./express-force-domain')('http://www.example.com') );

Package on npm: https://npmjs.org/package/express-force-domain



来源:https://stackoverflow.com/questions/9132891/redirect-non-www-to-www-with-node-js-and-express

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!