L
L
lohmag2016-10-19 18:07:54
Node.js
lohmag, 2016-10-19 18:07:54

How to set up nginx+express.js?

There is a config in nginx:

location /mac-address/ {
            proxy_pass http://127.0.0.1:8001/;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-NginX-Proxy true;
            proxy_redirect off;

It sends an application to the node, which then routes inside itself, the application uses express.js / Routing works fine
app.get('/login', function(request, response) {}
But if you add a redirect inside express - res.redirect('/login');, then the transition starts along crooked links, for example, instead of mysite/ mac-address/login makes a GET request to mysite/login , the problem, as I understand it, is in nginx, but I can’t figure out how to fix it.
app.get('/', ensureAuthenticated,
   function(request, response) {
  fs.readFile('../index.html', function(err, file) {
    if (err) {
      // write an error response or nothing here
      return;
    }
    response.writeHead(200, {'Content-Type': 'text/html'});
    response.end(file, "utf-8");
  });
});

function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) {
    return next();
  } else {
   res.redirect('/login');
  }
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
L
lohmag, 2016-10-20
@lohmag

The goal is to make sure that the url mysite/mac-address does not differ from just the root / and that the node application doesn't know about the existence of mac-address at all.
PS I managed to set up the redirect as I wanted, but I didn’t understand why it didn’t work right away

location /mac-address/ {
            proxy_pass http://127.0.0.1:8001/;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-NginX-Proxy true;
            proxy_redirect / /mac-address/;
        }

app.post('/login',
   passport.authenticate('local', { failureRedirect: '/login' }),
   function(req, res) {
     res.redirect('/');
   });

A
Andrey Burov, 2016-10-19
@BuriK666

Probably like this:
nginx.org/en/docs/http/ngx_http_proxy_module.html#...

S
s2dent, 2016-10-20
@s2dent

So it's logical, res.redirect('/login'); means that the client, in HTTP headers, will be given a status with a 302 code and a redirect address where the client (browser) should go. That is, let's say the user visits the address "mysite/mac-address/", and the server redirects him to "mysite/login", where he tries to reach, naturally Nginx will not process this request, but if it is " res.redirect('/mac-address/login');", then everything should work as you want.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question