nodejs相当于.htaccess

时间:2013-06-19 18:54:33

标签: node.js .htaccess

是否可以在node.js

中构建这样的代码
<IfModule mod_rewrite.c>
     RewriteEngine on

     RewriteCond% {REQUEST_URI}! / (View) / [NC]
     RewriteCond% {REQUEST_FILENAME}!-F
     RewriteRule ^ (. *) $ Index.html [L, QSA]

</IfModule>

url显示路由不是“view”,文件也不存在,然后写index.html

使用expressconnect

之类的内容

更新:!/(view)/express的路线node.js需要正则表达式。

3 个答案:

答案 0 :(得分:17)

你试过了吗?

  1. Serve statics
  2. 抓取/查看网址
  3. 抓住其他一切

    app.configure(function(){
      app.use(express.static(__dirname+'/public')); // Catch static files
      app.use(app.routes);
    });
    
    // Catch /view and do whatever you like
    app.all('/view', function(req, res) {
    
    });
    
    // Catch everything else and redirect to /index.html
    // Of course you could send the file's content with fs.readFile to avoid
    // using redirects
    app.all('*', function(req, res) { 
      res.redirect('/index.html'); 
    });
    
  4. OR

    1. Serve statics
    2. 检查网址是否为/ view

      app.configure(function(){
        app.use(express.static(__dirname+'/public')); // Catch static files
        app.use(function(req, res, next) {
          if (req.url == '/view') {
            next();
          } else {
            res.redirect('/index.html');
          }
        });
      });
      
    3. OR

      1. 照常捕捉静电
      2. Catch NOT / view

        app.configure(function(){
          app.use(express.static(__dirname+'/public')); // Catch static files
          app.use(app.routes);
        });
        
        app.get(/^(?!\/view$).*$/, function(req, res) {
          res.redirect('/index.html');
        });
        

答案 1 :(得分:4)

最终结构是:

var express = require('express'), url = require('url');

var app = express();
app.use(function(req, res, next) {
    console.log('%s %s', req.method, req.url);
    next();
});
app.configure(function() {
    var pub_dir = __dirname + '/public';
    app.set('port', process.env.PORT || 8080);
    app.engine('.html', require('ejs').__express);
    app.set('views', __dirname + '/views');
    app.set('view engine', 'html');
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(express.cookieParser());
    app.use(express.static(pub_dir));
    app.use(app.router);
});
app.get('/*', function(req, res) {
    if (req.xhr) {
        var pathname = url.parse(req.url).pathname;
        res.sendfile('index.html', {root: __dirname + '/public' + pathname});
    } else {
        res.render('index');
    }
});

app.listen(app.get('port'));

谢谢大家。 PD:使用模块ejs

渲染html

答案 2 :(得分:0)

我建议使用明确的中间件urlrewrite。

例如,如果您不处理反向代理上的重写,并且使用Express并希望正则表达式支持灵活性,请使用:https://www.npmjs.com/package/express-urlrewrite