You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

493 lines
16 KiB

7 years ago
  1. <p align="center">
  2. <img src="https://raw.github.com/nodejitsu/node-http-proxy/master/doc/logo.png"/>
  3. </p>
  4. node-http-proxy
  5. =======
  6. <p align="left">
  7. <a href="https://travis-ci.org/nodejitsu/node-http-proxy" target="_blank">
  8. <img src="https://travis-ci.org/nodejitsu/node-http-proxy.png"/></a>&nbsp;&nbsp;
  9. <a href="https://coveralls.io/r/nodejitsu/node-http-proxy" target="_blank">
  10. <img src="https://coveralls.io/repos/nodejitsu/node-http-proxy/badge.png"/></a>
  11. </p>
  12. `node-http-proxy` is an HTTP programmable proxying library that supports
  13. websockets. It is suitable for implementing components such as reverse
  14. proxies and load balancers.
  15. ### Table of Contents
  16. * [Installation](#installation)
  17. * [Upgrading from 0.8.x ?](#upgrading-from-08x-)
  18. * [Core Concept](#core-concept)
  19. * [Use Cases](#use-cases)
  20. * [Setup a basic stand-alone proxy server](#setup-a-basic-stand-alone-proxy-server)
  21. * [Setup a stand-alone proxy server with custom server logic](#setup-a-stand-alone-proxy-server-with-custom-server-logic)
  22. * [Setup a stand-alone proxy server with proxy request header re-writing](#setup-a-stand-alone-proxy-server-with-proxy-request-header-re-writing)
  23. * [Modify a response from a proxied server](#modify-a-response-from-a-proxied-server)
  24. * [Setup a stand-alone proxy server with latency](#setup-a-stand-alone-proxy-server-with-latency)
  25. * [Using HTTPS](#using-https)
  26. * [Proxying WebSockets](#proxying-websockets)
  27. * [Options](#options)
  28. * [Listening for proxy events](#listening-for-proxy-events)
  29. * [Shutdown](#shutdown)
  30. * [Miscellaneous](#miscellaneous)
  31. * [Test](#test)
  32. * [ProxyTable API](#proxytable-api)
  33. * [Logo](#logo)
  34. * [Contributing and Issues](#contributing-and-issues)
  35. * [License](#license)
  36. ### Installation
  37. `npm install http-proxy --save`
  38. **[Back to top](#table-of-contents)**
  39. ### Upgrading from 0.8.x ?
  40. Click [here](UPGRADING.md)
  41. **[Back to top](#table-of-contents)**
  42. ### Core Concept
  43. A new proxy is created by calling `createProxyServer` and passing
  44. an `options` object as argument ([valid properties are available here](lib/http-proxy.js#L33-L50))
  45. ```javascript
  46. var httpProxy = require('http-proxy');
  47. var proxy = httpProxy.createProxyServer(options); // See (†)
  48. ```
  49. †Unless listen(..) is invoked on the object, this does not create a webserver. See below.
  50. An object will be returned with four methods:
  51. * web `req, res, [options]` (used for proxying regular HTTP(S) requests)
  52. * ws `req, socket, head, [options]` (used for proxying WS(S) requests)
  53. * listen `port` (a function that wraps the object in a webserver, for your convenience)
  54. * close `[callback]` (a function that closes the inner webserver and stops listening on given port)
  55. It is then possible to proxy requests by calling these functions
  56. ```javascript
  57. http.createServer(function(req, res) {
  58. proxy.web(req, res, { target: 'http://mytarget.com:8080' });
  59. });
  60. ```
  61. Errors can be listened on either using the Event Emitter API
  62. ```javascript
  63. proxy.on('error', function(e) {
  64. ...
  65. });
  66. ```
  67. or using the callback API
  68. ```javascript
  69. proxy.web(req, res, { target: 'http://mytarget.com:8080' }, function(e) { ... });
  70. ```
  71. When a request is proxied it follows two different pipelines ([available here](lib/http-proxy/passes))
  72. which apply transformations to both the `req` and `res` object.
  73. The first pipeline (incoming) is responsible for the creation and manipulation of the stream that connects your client to the target.
  74. The second pipeline (outgoing) is responsible for the creation and manipulation of the stream that, from your target, returns data
  75. to the client.
  76. **[Back to top](#table-of-contents)**
  77. ### Use Cases
  78. #### Setup a basic stand-alone proxy server
  79. ```js
  80. var http = require('http'),
  81. httpProxy = require('http-proxy');
  82. //
  83. // Create your proxy server and set the target in the options.
  84. //
  85. httpProxy.createProxyServer({target:'http://localhost:9000'}).listen(8000); // See (†)
  86. //
  87. // Create your target server
  88. //
  89. http.createServer(function (req, res) {
  90. res.writeHead(200, { 'Content-Type': 'text/plain' });
  91. res.write('request successfully proxied!' + '\n' + JSON.stringify(req.headers, true, 2));
  92. res.end();
  93. }).listen(9000);
  94. ```
  95. †Invoking listen(..) triggers the creation of a web server. Otherwise, just the proxy instance is created.
  96. **[Back to top](#table-of-contents)**
  97. #### Setup a stand-alone proxy server with custom server logic
  98. This example show how you can proxy a request using your own HTTP server
  99. and also you can put your own logic to handle the request.
  100. ```js
  101. var http = require('http'),
  102. httpProxy = require('http-proxy');
  103. //
  104. // Create a proxy server with custom application logic
  105. //
  106. var proxy = httpProxy.createProxyServer({});
  107. //
  108. // Create your custom server and just call `proxy.web()` to proxy
  109. // a web request to the target passed in the options
  110. // also you can use `proxy.ws()` to proxy a websockets request
  111. //
  112. var server = http.createServer(function(req, res) {
  113. // You can define here your custom logic to handle the request
  114. // and then proxy the request.
  115. proxy.web(req, res, { target: 'http://127.0.0.1:5060' });
  116. });
  117. console.log("listening on port 5050")
  118. server.listen(5050);
  119. ```
  120. **[Back to top](#table-of-contents)**
  121. #### Setup a stand-alone proxy server with proxy request header re-writing
  122. This example shows how you can proxy a request using your own HTTP server that
  123. modifies the outgoing proxy request by adding a special header.
  124. ```js
  125. var http = require('http'),
  126. httpProxy = require('http-proxy');
  127. //
  128. // Create a proxy server with custom application logic
  129. //
  130. var proxy = httpProxy.createProxyServer({});
  131. // To modify the proxy connection before data is sent, you can listen
  132. // for the 'proxyReq' event. When the event is fired, you will receive
  133. // the following arguments:
  134. // (http.ClientRequest proxyReq, http.IncomingMessage req,
  135. // http.ServerResponse res, Object options). This mechanism is useful when
  136. // you need to modify the proxy request before the proxy connection
  137. // is made to the target.
  138. //
  139. proxy.on('proxyReq', function(proxyReq, req, res, options) {
  140. proxyReq.setHeader('X-Special-Proxy-Header', 'foobar');
  141. });
  142. var server = http.createServer(function(req, res) {
  143. // You can define here your custom logic to handle the request
  144. // and then proxy the request.
  145. proxy.web(req, res, {
  146. target: 'http://127.0.0.1:5060'
  147. });
  148. });
  149. console.log("listening on port 5050")
  150. server.listen(5050);
  151. ```
  152. **[Back to top](#table-of-contents)**
  153. #### Modify a response from a proxied server
  154. Sometimes when you have received a HTML/XML document from the server of origin you would like to modify it before forwarding it on.
  155. [Harmon](https://github.com/No9/harmon) allows you to do this in a streaming style so as to keep the pressure on the proxy to a minimum.
  156. **[Back to top](#table-of-contents)**
  157. #### Setup a stand-alone proxy server with latency
  158. ```js
  159. var http = require('http'),
  160. httpProxy = require('http-proxy');
  161. //
  162. // Create a proxy server with latency
  163. //
  164. var proxy = httpProxy.createProxyServer();
  165. //
  166. // Create your server that makes an operation that waits a while
  167. // and then proxies the request
  168. //
  169. http.createServer(function (req, res) {
  170. // This simulates an operation that takes 500ms to execute
  171. setTimeout(function () {
  172. proxy.web(req, res, {
  173. target: 'http://localhost:9008'
  174. });
  175. }, 500);
  176. }).listen(8008);
  177. //
  178. // Create your target server
  179. //
  180. http.createServer(function (req, res) {
  181. res.writeHead(200, { 'Content-Type': 'text/plain' });
  182. res.write('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
  183. res.end();
  184. }).listen(9008);
  185. ```
  186. **[Back to top](#table-of-contents)**
  187. #### Using HTTPS
  188. You can activate the validation of a secure SSL certificate to the target connection (avoid self signed certs), just set `secure: true` in the options.
  189. ##### HTTPS -> HTTP
  190. ```js
  191. //
  192. // Create the HTTPS proxy server in front of a HTTP server
  193. //
  194. httpProxy.createServer({
  195. target: {
  196. host: 'localhost',
  197. port: 9009
  198. },
  199. ssl: {
  200. key: fs.readFileSync('valid-ssl-key.pem', 'utf8'),
  201. cert: fs.readFileSync('valid-ssl-cert.pem', 'utf8')
  202. }
  203. }).listen(8009);
  204. ```
  205. ##### HTTPS -> HTTPS
  206. ```js
  207. //
  208. // Create the proxy server listening on port 443
  209. //
  210. httpProxy.createServer({
  211. ssl: {
  212. key: fs.readFileSync('valid-ssl-key.pem', 'utf8'),
  213. cert: fs.readFileSync('valid-ssl-cert.pem', 'utf8')
  214. },
  215. target: 'https://localhost:9010',
  216. secure: true // Depends on your needs, could be false.
  217. }).listen(443);
  218. ```
  219. **[Back to top](#table-of-contents)**
  220. #### Proxying WebSockets
  221. You can activate the websocket support for the proxy using `ws:true` in the options.
  222. ```js
  223. //
  224. // Create a proxy server for websockets
  225. //
  226. httpProxy.createServer({
  227. target: 'ws://localhost:9014',
  228. ws: true
  229. }).listen(8014);
  230. ```
  231. Also you can proxy the websocket requests just calling the `ws(req, socket, head)` method.
  232. ```js
  233. //
  234. // Setup our server to proxy standard HTTP requests
  235. //
  236. var proxy = new httpProxy.createProxyServer({
  237. target: {
  238. host: 'localhost',
  239. port: 9015
  240. }
  241. });
  242. var proxyServer = http.createServer(function (req, res) {
  243. proxy.web(req, res);
  244. });
  245. //
  246. // Listen to the `upgrade` event and proxy the
  247. // WebSocket requests as well.
  248. //
  249. proxyServer.on('upgrade', function (req, socket, head) {
  250. proxy.ws(req, socket, head);
  251. });
  252. proxyServer.listen(8015);
  253. ```
  254. **[Back to top](#table-of-contents)**
  255. ### Options
  256. `httpProxy.createProxyServer` supports the following options:
  257. * **target**: url string to be parsed with the url module
  258. * **forward**: url string to be parsed with the url module
  259. * **agent**: object to be passed to http(s).request (see Node's [https agent](http://nodejs.org/api/https.html#https_class_https_agent) and [http agent](http://nodejs.org/api/http.html#http_class_http_agent) objects)
  260. * **ssl**: object to be passed to https.createServer()
  261. * **ws**: true/false, if you want to proxy websockets
  262. * **xfwd**: true/false, adds x-forward headers
  263. * **secure**: true/false, if you want to verify the SSL Certs
  264. * **toProxy**: true/false, passes the absolute URL as the `path` (useful for proxying to proxies)
  265. * **prependPath**: true/false, Default: true - specify whether you want to prepend the target's path to the proxy path
  266. * **ignorePath**: true/false, Default: false - specify whether you want to ignore the proxy path of the incoming request (note: you will have to append / manually if required).
  267. * **localAddress**: Local interface string to bind for outgoing connections
  268. * **changeOrigin**: true/false, Default: false - changes the origin of the host header to the target URL
  269. * **preserveHeaderKeyCase**: true/false, Default: false - specify whether you want to keep letter case of response header key
  270. * **auth**: Basic authentication i.e. 'user:password' to compute an Authorization header.
  271. * **hostRewrite**: rewrites the location hostname on (201/301/302/307/308) redirects.
  272. * **autoRewrite**: rewrites the location host/port on (201/301/302/307/308) redirects based on requested host/port. Default: false.
  273. * **protocolRewrite**: rewrites the location protocol on (201/301/302/307/308) redirects to 'http' or 'https'. Default: null.
  274. * **cookieDomainRewrite**: rewrites domain of `set-cookie` headers. Possible values:
  275. * `false` (default): disable cookie rewriting
  276. * String: new domain, for example `cookieDomainRewrite: "new.domain"`. To remove the domain, use `cookieDomainRewrite: ""`.
  277. * Object: mapping of domains to new domains, use `"*"` to match all domains.
  278. For example keep one domain unchanged, rewrite one domain and remove other domains:
  279. ```
  280. cookieDomainRewrite: {
  281. "unchanged.domain": "unchanged.domain",
  282. "old.domain": "new.domain",
  283. "*": ""
  284. }
  285. ```
  286. * **headers**: object with extra headers to be added to target requests.
  287. * **proxyTimeout**: timeout (in millis) when proxy receives no response from target
  288. **NOTE:**
  289. `options.ws` and `options.ssl` are optional.
  290. `options.target` and `options.forward` cannot both be missing
  291. If you are using the `proxyServer.listen` method, the following options are also applicable:
  292. * **ssl**: object to be passed to https.createServer()
  293. * **ws**: true/false, if you want to proxy websockets
  294. **[Back to top](#table-of-contents)**
  295. ### Listening for proxy events
  296. * `error`: The error event is emitted if the request to the target fail. **We do not do any error handling of messages passed between client and proxy, and messages passed between proxy and target, so it is recommended that you listen on errors and handle them.**
  297. * `proxyReq`: This event is emitted before the data is sent. It gives you a chance to alter the proxyReq request object. Applies to "web" connections
  298. * `proxyReqWs`: This event is emitted before the data is sent. It gives you a chance to alter the proxyReq request object. Applies to "websocket" connections
  299. * `proxyRes`: This event is emitted if the request to the target got a response.
  300. * `open`: This event is emitted once the proxy websocket was created and piped into the target websocket.
  301. * `close`: This event is emitted once the proxy websocket was closed.
  302. * (DEPRECATED) `proxySocket`: Deprecated in favor of `open`.
  303. ```js
  304. var httpProxy = require('http-proxy');
  305. // Error example
  306. //
  307. // Http Proxy Server with bad target
  308. //
  309. var proxy = httpProxy.createServer({
  310. target:'http://localhost:9005'
  311. });
  312. proxy.listen(8005);
  313. //
  314. // Listen for the `error` event on `proxy`.
  315. proxy.on('error', function (err, req, res) {
  316. res.writeHead(500, {
  317. 'Content-Type': 'text/plain'
  318. });
  319. res.end('Something went wrong. And we are reporting a custom error message.');
  320. });
  321. //
  322. // Listen for the `proxyRes` event on `proxy`.
  323. //
  324. proxy.on('proxyRes', function (proxyRes, req, res) {
  325. console.log('RAW Response from the target', JSON.stringify(proxyRes.headers, true, 2));
  326. });
  327. //
  328. // Listen for the `open` event on `proxy`.
  329. //
  330. proxy.on('open', function (proxySocket) {
  331. // listen for messages coming FROM the target here
  332. proxySocket.on('data', hybiParseAndLogMessage);
  333. });
  334. //
  335. // Listen for the `close` event on `proxy`.
  336. //
  337. proxy.on('close', function (res, socket, head) {
  338. // view disconnected websocket connections
  339. console.log('Client disconnected');
  340. });
  341. ```
  342. **[Back to top](#table-of-contents)**
  343. ### Shutdown
  344. * When testing or running server within another program it may be necessary to close the proxy.
  345. * This will stop the proxy from accepting new connections.
  346. ```js
  347. var proxy = new httpProxy.createProxyServer({
  348. target: {
  349. host: 'localhost',
  350. port: 1337
  351. }
  352. });
  353. proxy.close();
  354. ```
  355. **[Back to top](#table-of-contents)**
  356. ### Miscellaneous
  357. #### ProxyTable API
  358. A proxy table API is available through this add-on [module](https://github.com/donasaur/http-proxy-rules), which lets you define a set of rules to translate matching routes to target routes that the reverse proxy will talk to.
  359. #### Test
  360. ```
  361. $ npm test
  362. ```
  363. #### Logo
  364. Logo created by [Diego Pasquali](http://dribbble.com/diegopq)
  365. **[Back to top](#table-of-contents)**
  366. ### Contributing and Issues
  367. * Search on Google/Github
  368. * If you can't find anything, open an issue
  369. * If you feel comfortable about fixing the issue, fork the repo
  370. * Commit to your local branch (which must be different from `master`)
  371. * Submit your Pull Request (be sure to include tests and update documentation)
  372. **[Back to top](#table-of-contents)**
  373. ### License
  374. >The MIT License (MIT)
  375. >
  376. >Copyright (c) 2010 - 2016 Charlie Robbins, Jarrett Cruger & the Contributors.
  377. >
  378. >Permission is hereby granted, free of charge, to any person obtaining a copy
  379. >of this software and associated documentation files (the "Software"), to deal
  380. >in the Software without restriction, including without limitation the rights
  381. >to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  382. >copies of the Software, and to permit persons to whom the Software is
  383. >furnished to do so, subject to the following conditions:
  384. >
  385. >The above copyright notice and this permission notice shall be included in
  386. >all copies or substantial portions of the Software.
  387. >
  388. >THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  389. >IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  390. >FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  391. >AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  392. >LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  393. >OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  394. >THE SOFTWARE.