简体   繁体   English

Node.js非www到www重定向不起作用

[英]Node.js non www to www redirect does not working

I have referred to this: https://www.hacksparrow.com/how-to-forward-non-www-to-www-domain-name-and-vice-versa-in-node-js-express.html 我已经提到了这一点: https : //www.hacksparrow.com/how-to-forward-non-www-to-www-domain-name-and-vice-versa-in-node-js-express.html

And to other Stackoverflow questions, but I still get errors when doing what they said: 和其他Stackoverflow问题一样,但是当他们说什么时,我仍然遇到错误:

This code: 这段代码:

app.get('/*', function(req, res, next) {
    if (req.headers.host.match(/^www/) == null ) res.redirect('http://www.' + req.headers.host + req.url, 301);
    else next();
});

Redirects me to www.localhost:8080 ... 将我重定向到www.localhost:8080 ...

I have tried other syntax but still not working: 我尝试了其他语法,但仍无法正常工作:

app.get('/*', function(req, res, next) {
    if (req.headers.host.match(/^www/) == null ) res.redirect('http://www.ride4you.co.il', 301);
    else next();
});

(It redirects too many time until Chrome is timedout). (它重定向太多时间,直到Chrome超时)。

My question is how to fix this, in order to redirect ANY kind of addresses in the web address bar to https://www.mydomain.co.il , for example: mydomain.com www.mydomain.co.il http://mydomain.co.il , I want all of them to point to the first I wrote. 我的问题是如何解决此问题,以便将网址栏中的任何类型的地址重定向到https://www.mydomain.co.il ,例如:mydomain.com www.mydomain.co.il http:/ /mydomain.co.il ,我希望所有人都指向我写的第一个。

Thanks. 谢谢。

Only allow the specific host you want through, and catch the unlikely case that it's a HTTP/1.0 without a host header. 只允许您想要的特定主机通过,并捕获不太可能的情况,即它是没有主机头的HTTP / 1.0。

app.use((req, res, next) => {
    if ( !req.headers.host || req.headers.host === 'www.mydomain.co.il' ) return next() 
    res.redirect('http://www.mydomain.co.il/', 301)
})

You can keep the users original request path in the new URL. 您可以将用户的原始请求路径保留在新URL中。

res.redirect('http://www.mydomain.co.il'+req.originalUrl, 301)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM