将我的静态站点移动到新域,同时需要将站点上每个URL的最后一个斜杠删除,并使用Lambda函数发送301响应。这是它的外观:
oldsite.com/any-page /将是newsite.com/any-page
[我找到了一个代码示例来帮助我更改域,但是现在旧站点上的每个页面都将指向新站点的主页,而无需考虑更改路径功能。
这是我现在正在使用的代码,对于路径切换来说有些不正确:
'use strict';
exports.handler = (event, context, callback) => {
/*
* Generate HTTP redirect response with 301 status code and Location header.
*/
const request = event.Records[0].cf.request;
// get the original URL path
const path = request.uri
const baseURI = 'https://newsite.com'
// construct the response
const response = {
status: '301',
statusDescription: 'Found',
headers: {
location: [{
key: 'Location',
value: baseURI,
}],
},
};
// Configure the URL redirects
switch(path) {
case /\/.*\//:
response.headers.location[0].value = baseURI + /\/.*/;
break;
default:
response.headers.location[0].value = baseURI;
}
callback(null, response);
};
自从我尝试实际路径以来,这里的罪魁祸首似乎是正则表达式:
switch(path) {
case '/foo/':
response.headers.location[0].value = baseURI + '/foo';
break;
它工作完美,做出了切换。我在这里想念什么?
经过研究和探索,我管理了一个实际的代码,该代码可以工作,并且看起来比原始代码更有效。至少对于这个特定用例,它似乎对我有用。我可以根据需要添加更多条件。
'use strict';
exports.handler = (event, context, callback) => {
/*
* Generate HTTP redirect response with 301 status code and Location header.
*/
const request = event.Records[0].cf.request;
// get the original URL path
const baseURI = 'https://newsite.com'
const path = request.uri.replace(/\/$/, '')
const newURI = baseURI+path
// construct the response
const response = {
status: '301',
statusDescription: 'Found',
headers: {
location: [{
key: 'Location',
value: newURI,
}],
},
};
callback(null, response);
};