Let’s say that:
- Your images and CSS files are in your project’s
static
directory, AND
- Your
baseof.html
looks something like this:
<html>>
<head>
<link rel="stylesheet" href="/css/main.css">
</head>
<body>
<img src="/images/b.jpg">
<a href="/posts/post-1">Post 1</a>
</body>
</html>
When you serve the site from a subdirectory, all of the links will fail. There are several ways to handle this.
Method 1 - Hardcode the links
<link rel="stylesheet" href="/subdirectory/css/main.css">
This is a bad idea.
Method 2 - Enable the canonifyURLs
setting
Because these links begin with a slash, you can set canonifyURLs
to true
in your site configuration. You can read this to learn more about how canonifyURLs
works.
The canonifyURLs
setting will only affect src
, href
, url
, action
, and srcset
attributes where the value begins with a slash. It will affect links in both templates and content files.
If you read the post that I referenced above, you can see that the canonifyURLs
process is dumb. It just prepends the baseURL to the link. This ignores things like permalinks
, uglyURLs
, url
and slug
in front matter, etc.
Although it works for some things, I wouldn’t use it.
Method 3 - Use the relURL
function:
<html>>
<head>
<link rel="stylesheet" href="{{ "css/main.css" | relURL }}">
</head>
<body>
<img src="{{ "images/b.jpg" | relURL}}">
<a href="{{ "posts/post-1" | relURL }}">Post 1</a>
</body>
</html>
Of the methods described above, this is the best. Note that the URLs must not have a leading slash.
But what about the image references in CSS? For example:
body {
background: url(/images/a.jpg);
}
The canonifyURLs
setting will not affect this, and you can’t place template code in a CSS file without executing it as a template. If you want to handle this quickly, I would hardcode the URLs.
Method 4 - Use the .RelPermalink
method with everything
I use the static directory for favicons and robots.txt. That’s it. Everything else is either a page resource or a global resource. This approach requires:
- An image render hook
- A link render hook
- Use of the
resources.Get
and .Resources.Get
methods
- Executing the CSS file as a template, or passing variables into Sass
It is not an easy exercise for a casual Hugo user.