在Node.js中将URL重定向到www可以通过以下步骤实现:
const http = require('http');
const server = http.createServer((req, res) => {
// 处理请求
});
server.listen(3000, () => {
console.log('Server is running on port 3000');
});
const http = require('http');
const server = http.createServer((req, res) => {
const { headers, url } = req;
const host = headers.host;
if (!host.startsWith('www.')) {
const redirectUrl = `https://www.${host}${url}`;
res.writeHead(301, { Location: redirectUrl });
res.end();
} else {
// 处理其他请求
}
});
server.listen(3000, () => {
console.log('Server is running on port 3000');
});
const http = require('http');
const https = require('https');
const fs = require('fs');
const options = {
key: fs.readFileSync('private-key.pem'),
cert: fs.readFileSync('public-cert.pem')
};
const server = http.createServer((req, res) => {
// HTTP重定向逻辑
});
const httpsServer = https.createServer(options, (req, res) => {
// HTTPS请求处理逻辑
});
server.listen(80, () => {
console.log('HTTP Server is running on port 80');
});
httpsServer.listen(443, () => {
console.log('HTTPS Server is running on port 443');
});
请注意,上述代码中的私钥和公共证书文件路径应根据你的实际情况进行更改。
这样,当用户访问不带www子域的URL时,Node.js服务器将自动将其重定向到带有www子域的URL。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云