1diff --git a/lib/pure/dynlib.nim b/lib/pure/dynlib.nim
2index f31ae94dd..debed9c07 100644
3--- a/lib/pure/dynlib.nim
4+++ b/lib/pure/dynlib.nim
5@@ -56,6 +56,9 @@
6
7 import strutils
8
9+when defined(nixbuild) and not defined(windows):
10+ import os
11+
12 type
13 LibHandle* = pointer ## a handle to a dynamically loaded library
14
15@@ -95,6 +98,25 @@ proc libCandidates*(s: string, dest: var seq[string]) =
16 libCandidates(prefix & middle & suffix, dest)
17 else:
18 add(dest, s)
19+ when defined(nixbuild) and not defined(windows):
20+ # Nix doesn't have a global library directory so
21+ # load libraries using an absolute path if one
22+ # can be derived from NIX_LDFLAGS.
23+ #
24+ # During Nix/NixOS packaging the line "define:nixbuild"
25+ # should be appended to the ../../config/nim.cfg file
26+ # to enable this behavior by default.
27+ #
28+ var libDirs = split(getEnv("LD_LIBRARY_PATH"), ':')
29+ for flag in split(replace(getEnv("NIX_LDFLAGS"), "\\ ", " ")):
30+ if flag.startsWith("-L"):
31+ libDirs.add(flag[2..flag.high])
32+ for lib in dest:
33+ for dir in libDirs:
34+ let abs = dir / lib
35+ if existsFile(abs):
36+ dest = @[abs]
37+ return
38
39 proc loadLibPattern*(pattern: string, globalSymbols = false): LibHandle =
40 ## loads a library with name matching `pattern`, similar to what `dlimport`