diff --git a/lib/plugins/tag/post_link.ts b/lib/plugins/tag/post_link.ts
index 67289df469..9aec591a9d 100644
--- a/lib/plugins/tag/post_link.ts
+++ b/lib/plugins/tag/post_link.ts
@@ -41,7 +41,13 @@ export = (ctx: Hexo) => {
const attrTitle = escapeHTML(post.title || post.slug);
if (escape === 'true') title = escapeHTML(title);
- const url = new URL(post.path, ctx.config.url).pathname + (hash ? `#${hash}` : '');
+ // guarantee the base url ends with a slash. (case of using a subdirectory in the url of the site)
+ let baseUrl = ctx.config.url;
+ if (!baseUrl.endsWith('/')) {
+ baseUrl += '/';
+ }
+
+ const url = new URL(post.path, baseUrl).pathname + (hash ? `#${hash}` : '');
const link = encodeURL(url);
return `${title}`;
diff --git a/test/scripts/tags/post_link.js b/test/scripts/tags/post_link.js
index 05839a8098..8d4d89f546 100644
--- a/test/scripts/tags/post_link.js
+++ b/test/scripts/tags/post_link.js
@@ -77,4 +77,9 @@ describe('post_link', () => {
it('should keep hash', () => {
postLink(['foo#bar']).should.eql('Hello world');
});
+
+ it('should keep subdir', () => {
+ hexo.config.url = 'http://example.com/subdir';
+ postLink(['foo']).should.eql('Hello world');
+ });
});