10

Maybe too basic of a question but wanted to see if there is more to it than I am thinking.

When configuring URLs (baseUrls, like https://my.app or relative URLs like /path/to/resource) either as a static variable, in configuration files or environment variables etc., what should my 'slash strategy' be?

One of my coworkers mentioned that I should always configure base URLs with a trailing slash (https://my.app/) and paths with a leading and trailing slash (/path/to/resource/) because in most cases when you concatenate these, you may end up with double slashes (http://my.app//path/to/resource/) but most tools can handle that. If the claim that most tools can handle it is true, this could be an attractive approach since all you need to know is to always use slashes everywhere.

The other solutions could either be to follow and be consistent with either one of these approaches:

  • No trailing slashes but always use leading ones (http://my.app, /path/to/resource)
  • No leading slashes, but always use trailing ones (http://my.app/, path/to/resource/)

Is there a best strategy? Would the strategies be dependent on the tools being used (like libraries that can handle one but not the other?)

c_maker
  • 8,310

2 Answers2

12

Do not use bare strings to record URIs. Most languages have a type for them that handles joining absolute and relative paths automatically, ensuring you never need to sorry about doubled (or missing) slashes. Using this type will save you no end of problems,

Jules
  • 17,880
  • 2
  • 38
  • 65
10

Always including a trailing slash on the base URL and omitting the leading slash on the relative URL would allow you to concatenate the two in a manner that matches the spec on combining a base URL with relative URL to derive a full URL (RFC1808, Section 4).

Doing it this way would allow you to have a consistent method that is also the least surprising.