HTTP Proxy Rules for Node-HTTP-Proxy

1.1.3 · abandoned · verified Wed Apr 22

http-proxy-rules is an add-on module designed to work with the `node-http-proxy` library, providing a mechanism to define and manage routing rules for a reverse proxy. It allows developers to configure a set of regular expression-based URL path matching rules that translate incoming client requests to different target URLs for the backend service. The current stable version is 1.1.3. As of current observations, the package appears to be unmaintained, with no recent releases or active development, suggesting a very slow or non-existent release cadence. Its primary differentiator is its simple, regex-based rule matching system built specifically to integrate with `node-http-proxy`, providing a more structured way to handle complex routing logic compared to manual request inspection within the proxy server. It prioritizes the first matching rule based on object key order.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to set up an HTTP proxy server using `http-proxy-rules` to define routing logic and `node-http-proxy` to handle the actual proxying. It creates a proxy server on port 6010 that routes requests based on URL path patterns to different target backend services, with a default fallback. This shows how to initialize `HttpProxyRules`, define regex-based rules, and use the `match` method within an `http-proxy` server callback.

const http = require('http');
const httpProxy = require('http-proxy');
const HttpProxyRules = require('http-proxy-rules');

// Set up proxy rules instance
const proxyRules = new HttpProxyRules({
  rules: {
    '.*/api/v1/users': 'http://localhost:3001/users',
    '.*/api/v1/products/([0-9]+)': 'http://localhost:3002/items/$1',
    '/admin': 'http://localhost:3003/dashboard',
    '/images/(.*)': 'http://localhost:3004/assets/$1'
  },
  default: 'http://localhost:3000' // Default target if no rules match
});

// Create reverse proxy instance
const proxy = httpProxy.createProxy();

// Create http server that leverages reverse proxy instance
// and proxy rules to proxy requests to different targets
http.createServer(function(req, res) {
  const target = proxyRules.match(req);

  if (target) {
    console.log(`Proxying ${req.url} to ${target}`);
    return proxy.web(req, res, { target: target });
  } else {
    console.log(`No rule matched for ${req.url}. Using default.`);
    return proxy.web(req, res, { target: proxyRules.default });
  }
}).listen(6010, () => {
  console.log('Proxy server listening on port 6010');
  console.log('  - Try: http://localhost:6010/api/v1/users');
  console.log('  - Try: http://localhost:6010/api/v1/products/123');
  console.log('  - Try: http://localhost:6010/admin');
  console.log('  - Try: http://localhost:6010/images/logo.png');
  console.log('  - Try: http://localhost:6010/unknown-path');
});

view raw JSON →