HTTP Rewrite Middleware for Connect/Express
This package, `http-rewrite-middleware`, provides Nginx-inspired, regular expression-based URL rewriting functionality as a middleware for Connect and Express web servers. It allows developers to define rules for internal rewrites (where the server processes the new URL internally without notifying the client) or external HTTP 301 (permanent) or 302 (temporary) redirects (where the client is instructed to request a new URL). The current version available is 0.1.6, though the provided README refers to v0.1.5. Its `node >= 0.8.0` engine requirement and low version number indicate that the package has likely not seen significant active development in many years, suggesting it is either abandoned or in a very minimal maintenance state. Its primary differentiators are its straightforward, rule-based approach for managing both internal URL transformations and client-side redirects, similar to how Nginx's `rewrite` module operates, making it a direct successor to `grunt-connect-rewrite` for Grunt-based setups.
Common errors
-
TypeError: Cannot read properties of undefined (reading 'getMiddleware') or similar
cause The `http-rewrite-middleware` module was not correctly installed or imported, leading to `rewriteModule` being undefined.fixVerify that `http-rewrite-middleware` is listed in your `package.json` and installed (`npm install`). Ensure `const rewriteModule = require('http-rewrite-middleware');` is correctly placed and spelled. -
Cannot GET /original-url (or a rewritten URL) after applying middleware.
cause The rewrite rule matched and redirected/rewrote to a new path, but there is no subsequent middleware or route handler configured to serve content at that new path.fixEnsure that after a rewrite, the target URL (`__to__`) corresponds to an existing static file, a defined route, or another middleware capable of handling the request. For debugging, enable `verbose: true` to confirm which rules are matching.
Warnings
- gotcha The order of middleware is crucial. `http-rewrite-middleware` should typically be placed before static file serving or other routing middleware to ensure rewrites occur before other handlers process the original URL.
- gotcha Understand the difference between internal rewrites and HTTP redirects. Omitting the `redirect` option results in an internal rewrite (server handles the new path, client is unaware). Specifying `redirect: 'permanent'` or `redirect: 'temporary'` sends an HTTP 301 or 302 status, respectively, instructing the client to request the new URL.
- gotcha Regular expressions in the `from` field must be valid JavaScript RegExp strings. Incorrect or overly broad regular expressions can lead to unintended rewrites or redirects, affecting application behavior.
Install
-
npm install http-rewrite-middleware -
yarn add http-rewrite-middleware -
pnpm add http-rewrite-middleware
Imports
- rewriteModule
const rewriteModule = require('http-rewrite-middleware'); - getMiddleware
const rewriteMiddleware = rewriteModule.getMiddleware([...rules]);
- RuleOptions
{ from: '^/old$', to: '/new', redirect: 'permanent' }
Quickstart
const express = require('express');
const rewriteModule = require('http-rewrite-middleware');
const app = express();
// Define rewrite rules
const rewriteRules = [
// Internal rewrite: /old-path -> /new-path
{from: '^/old-path$', to: '/new-path'},
// Internal rewrite with capture group: /api/v1/users -> /api/v2/users
{from: '^/api/v1/(.*)$', to: '/api/v2/$1'},
// 301 Permanent Redirect: /legacy -> /modern
{from: '^/legacy$', to: '/modern', redirect: 'permanent'},
// 302 Temporary Redirect: /temp-page -> /under-construction
{from: '^/temp-page$', to: '/under-construction', redirect: 'temporary'}
];
// Apply the rewrite middleware first, with verbose logging
app.use(rewriteModule.getMiddleware(rewriteRules, { verbose: true }));
// Example routes after rewrite
app.get('/new-path', (req, res) => {
res.send('Welcome to the new path (internal rewrite successful)!');
});
app.get('/api/v2/users', (req, res) => {
res.send('Accessing API v2 users endpoint.');
});
app.get('/modern', (req, res) => {
res.send('You have been permanently redirected here.');
});
app.get('/under-construction', (req, res) => {
res.send('This page is temporarily here.');
});
app.get('/', (req, res) => {
res.send('Hello from the root!');
});
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Express server running on http://localhost:${PORT}`);
console.log('Try visiting the following URLs to see rewrites/redirects:');
console.log(`- http://localhost:${PORT}/old-path`);
console.log(`- http://localhost:${PORT}/api/v1/users`);
console.log(`- http://localhost:${PORT}/legacy`);
console.log(`- http://localhost:${PORT}/temp-page`);
});