Skip to content

Commit f583765

Browse files
authored
fix: enable redirection to a relative path (#168)
1 parent 607810c commit f583765

File tree

3 files changed

+31
-2
lines changed

3 files changed

+31
-2
lines changed

src/no-dead-link.ts

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -183,16 +183,29 @@ const createCheckAliveURL = (ruleOptions: Options) => {
183183
const res = await fetchWithDefaults(uri, opts);
184184
// redirected
185185
if (isRedirect(res.status)) {
186-
const redirectedUrl = res.headers.get("Location");
186+
const location = res.headers.get("Location");
187187
// Status code is 301 or 302, but Location header is not set
188-
if (redirectedUrl === null) {
188+
if (location === null) {
189189
return {
190190
ok: false,
191191
redirected: true,
192192
redirectTo: null,
193193
message: `${res.status} ${res.statusText}`
194194
};
195195
}
196+
197+
const redirectedUrl = isRelative(location)
198+
? URL.parse(location, URL.parse(uri)?.origin)?.href
199+
: location;
200+
if (!redirectedUrl) {
201+
return {
202+
ok: false,
203+
redirected: true,
204+
redirectTo: null,
205+
message: `${res.status} ${res.statusText}`
206+
};
207+
}
208+
196209
const finalRes = await fetchWithDefaults(redirectedUrl, { ...opts, redirect: "follow" });
197210
const url = URL.parse(uri);
198211
const hash = url?.hash || null;

test/no-dead-link.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,13 @@ tester.run("no-dead-link", rule, {
121121
ignoreRedirects: true
122122
}
123123
},
124+
// Test whether redirection to a relative path is possible
125+
{
126+
text: `should handle relative redirect: ${TEST_SERVER_URL}/301-relative`,
127+
options: {
128+
ignoreRedirects: true
129+
}
130+
},
124131
// Test User-Agent requirement
125132
{
126133
text: `should treat 200 OK when User-Agent is provided: ${TEST_SERVER_URL}/user-agent-required`,

test/test-server.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,15 @@ export async function startTestServer(options: TestServerOptions = {}): Promise<
7272
res.end("Moved Permanently");
7373
break;
7474

75+
case "/301-relative":
76+
// Redirect to a relative URL
77+
res.writeHead(301, {
78+
Location: `200`,
79+
"Content-Type": "text/plain"
80+
});
81+
res.end("Moved Permanently");
82+
break;
83+
7584
case "/user-agent-required":
7685
// Requires specific User-Agent header
7786
if (req.headers["user-agent"] && req.headers["user-agent"].includes("Mozilla")) {

0 commit comments

Comments
 (0)