我想问你如何在node.js上使用mod_rewrite重写url。 connect-modrewrite
的创建者准备了示例here,但遗憾的是,如果express
此示例无效,则目前的版本方法configure
已被弃用。
标准语法是:
var app = require('express')();
var http = require('http').Server(app);
app.get('/', function(req, res){
res.sendfile('index.html');
});
http.listen(3000, function(){
console.log('listening for clients on *:3000');
});
我尝试将标准语法与connect-modrewrite
结合使用,例如:
var app = require('express')();
var http = require('http').Server(app);
var modRewrite = require('connect-modrewrite');
app.get(modRewrite([
'^/test$ /index.html',
'^/test/\\d*$ /index.html [L]',
'^/test/\\d*/\\d*$ /flag.html [L]'
]), function(req, res){
res.sendfile('index.html');
});
http.listen(3000, function(){
console.log('listening for clients on *:3000');
});
这会引发以下错误:
(...)node_modules/express/node_modules/path-to-regexp/index.js:34
.concat(strict ? '' : '/?')
我在这里被封锁了。如果有人有想法,我会很高兴。
答案 0 :(得分:0)
我得到了connect-modrewrite :)的作者的支持,这里有解决方案:
var app = require('express')();
var http = require('http').Server(app);
app.use(modRewrite([
'^/test$ /index.html',
'^/test/\\d*$ /index.html [L]',
'^/test/\\d*/\\d*$ /flag.html [L]'
]));
app.get('/index.html', function(req, res){
res.sendfile('index.html');
});
http.listen(3000, function(){
console.log('listening for clients on *:3000');
});
完美的作品!干杯!
答案 1 :(得分:0)
这是我根据Marek的回答使用的内容。这个想法是Express非静态路由不适用于此处。对于所有静态路由,您希望确保其中一些静态路由保持不变,其中一些将被重写到另一个目标,例如。在这里我确保其他所有内容都转到index.html,如果它不是来自样式,脚本,图像,字体和文件夹。
但如果您已经设置了快速路线,' / city',它仍然保持相同。
var modRewrite = require('connect-modrewrite');
app.use(modRewrite([
// express route has been taken care of, and won't enter here.
'^/styles/(.*)$ - [L]', // keep
'^/scripts/(.*)$ - [L]', // keep
'^/images/(.*)$ - [L]', // keep
'^/fonts/(.*)$ - [L]', // keep
'^/files/(.*)$ - [L]', // keep
'^/.*$ /index.html' // for whatever else, use index.html
//'^((?!api).)*$ /index.html' // for non-api routes, use index.html
]));
app.use(express.static(global.appRoot + config.www));