Hugo add prefix to all routes

Hello,

I need to host hugo site on an environment that has reverse proxy configured. In short, what happens is:

My hugo site is inside docker container
Reverse proxy is configured in a way that when I access: mysite/my-prefix/docs, the “my-prefix” tells the reverse proxy to route to my hugo site. Then it removes the prefix “my-prefix”, effectively accessing hugo-container/docs.

The problem:
All the urls inside the hugo container use normal routing, without the prefix, but due to reverse proxy I need to add the prefix “my-prefix” to all routes.

Example:
Hugo site wants to load the css files from mysite/my-styles.css, because thats the route inside the container. But from the browser it needs to access the css files through mysite.com/my-prefix/my-styles.css. I would like to be able to add this prefix at the beginning of every route

Only workaround I found so far was hardcoding /my-prefix before all .RelPermalink occurences in my theme, but that’s not the solution I want to stick with (though it works)

How to approach this problem?

You need to adjust your baseURL, e.g. in config.toml:

 baseURL="https://example.org/my-prefix"
1 Like

Thank you for your answer, here is why I had no success using the baseURL in a way that you provided:

the “https://example.org” in my case varies depending where I deploy my site. I need somehow a generic base (currently I use “/”) and then add prefix to it. So what I try is baseUrl="/my-prefix", but then when I run hugo server I get: Web Server is available at ///my-prefix/ and I cannot access it under any url

This may help: [SOLVED] What should be used for the value of .Site.BaseURL? - #16 by Hash_Borgir

Sure, you can set that via CLI argument or via OS environment.

The baseURL needs to be absolute with protocol etc. The above may work in some simple setups, but I would not recommend it.

Also, I would not try to construct URLs using .Site.BaseURL – either use the URLs Hugo produces (e.g. .RelPermalink) or use the built-in functions for this (e.g. relURL).

But that’s just my 50 cents, it’s not like I’m the expert on how Hugo works.

4 Likes

it’s not like I’m the expert on how Hugo works.

:rofl:

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.