nodejs equivalent of this .htaccess

后端 未结 3 602
-上瘾入骨i
-上瘾入骨i 2020-12-08 16:36

Is it possible to build a code like this in node.js?


     RewriteEngine on

     RewriteCond% {REQUEST_URI}! / (V         


        
相关标签:
3条回答
  • 2020-12-08 16:56

    Have you tried:

    1. Serve statics
    2. Catch /view URL
    3. Catch everything else

      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'); 
      });
      

    OR

    1. Serve statics
    2. Check if URL is /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');
          }
        });
      });
      

    OR

    1. Catch statics as usual
    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');
      });
      
    0 讨论(0)
  • 2020-12-08 17:03

    I would recommend using the express Middleware urlrewrite.

    If you don't handle rewrites on a reverse proxy for example and if using express and want regex support for flexibility use: https://www.npmjs.com/package/express-urlrewrite

    0 讨论(0)
  • 2020-12-08 17:17

    The final structure is:

    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'));
    

    Thanks everyone. PD: Render html with module ejs

    0 讨论(0)
提交回复
热议问题