Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

apache mod_rewrite equivalent for node.js?

Is there an equivalent module for Node.js that does what Apache's mod_rewrite does? or is there a standard language construct that provides equivalent functionality?

I'm just getting started with Node and looking to convert my server to this platform.

like image 759
ampersand Avatar asked May 04 '11 21:05

ampersand


People also ask

Does node JS replace Apache?

If you're prepared to re-write your PHP in JavaScript, then yes, Node. js can replace your Apache. If you place an Apache or NGINX instance running in reverse-proxy mode between your servers and your clients, you could handle some requests in JavaScript on Node.

What does node JS replace in LAMP stack?

Node js/Express to replace LAMP.

Do I need Apache with node?

No you won't need an Apache server. Because Node itself will serve as a Server Especially if you are working with Frameworks like Express. You don't need Nginx or Apache at all, but you can use if you want.

What is Apache mod_rewrite?

mod_rewrite is an Apache module that allows for server-side manipulation of requested URLs. mod_rewrite is an Apache module that allows for server-side manipulation of requested URLs. Incoming URLs are checked against a series of rules. The rules contain a regular expression to detect a particular pattern.


2 Answers

If you are looking for a good modrewrite library. You might want to look at connect-modrewrite

like image 128
einstein Avatar answered Sep 28 '22 15:09

einstein


If you have a HTTP server running with NodeJS you have 2 objects, request and response. The request contains the requested url. Using a require('url') you can parse this requested url and for example get the pathname that's requested.

What you then do with it, is up to your own code obviously. So based on the default example on www.nodejs.org you'd end up with something like this:

var http = require('http');
http.createServer(function (req, res) {
  var requestedURL = require('url').parse( req.url );
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.write( "You requested " + requestedURL.pathname + "\n" );
  res.end('Hello World\n');
}).listen(1337, "127.0.0.1");

Which you can test with http://127.0.0.1:1337/foo/bar. Where you can use requestedURL.pathname to determine what you'd want to do, ideally you'd create your own - or use a 3rd party - routing library. They are available, ExpressJS is a pretty famous NodeJS framework which might help take care of a lot of things for you, but I have no experience with it myself.

More information:

  • Now dead: [http://www.robsearles.com/2010/05/31/nodejs-tutorial-part-2-routing/]
  • http://expressjs.com/
like image 41
CharlesLeaf Avatar answered Sep 28 '22 17:09

CharlesLeaf