Su Cheung Su Cheung - 5 months ago 9
Linux Question

what's the difference between `/path/to/dir/` & `/path/to/dir`

Example:

nginx.conf

location ^~ /assets {
alias /path/to/assets;
}

location ^~ /assets {
alias /path/to/assets/;
}

location ^~ /assets/ {
alias /path/to/assets;
}

location ^~ /assets/ {
alias /path/to/assets/;
}


What's the difference between these codes?

Answer

It is a hack to ensure that path concatenations alway work.

Suppose I want to concatenate /someDirectory with a file inside that directory. And our system only allowed us to use the string /someDirectory. On some systems, they incorrectly allow for a relative (as opposed to absolute) path to start with a /. Whenever this happens a file might be found with the file string /file (incorrect because it should be relative not absolute). Then when the strings are concatenated the result could be:

  1. /someDirectory/file

But if the actual file path was typed correctly, it would ironically fail after concatenation:

  1. /someDirectoryfile

In the second case the file string file was correct but the result was incorrect. Thus some software allows for both absolute and terminal names for files, ie file or /file. They do this by making the root paths include or not include a trailing slash.

You could use a regular expression to detect all trailing slash conditions if you needed to. However, it is always the best convention to leave the slash on the leftmost portions of your path strings. That would mean /someDirectory/ is better than /someDirectory. This is because with /someDirectory if the next thing added to the path string is a /file, that would indicate by the / that /file is an absolute path and not relative. Thus leave slashes on the leftmost portion when doing string operations.

Comments