diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs
index c7089a295fc3d..6c90b2d2acbd8 100644
--- a/src/libsyntax/parse/parser.rs
+++ b/src/libsyntax/parse/parser.rs
@@ -6426,6 +6426,17 @@ impl<'a> Parser<'a> {
             self.directory.path.to_mut().push(&path.as_str());
             self.directory.ownership = DirectoryOwnership::Owned { relative: None };
         } else {
+            // We have to push on the current module name in the case of relative
+            // paths in order to ensure that any additional module paths from inline
+            // `mod x { ... }` come after the relative extension.
+            //
+            // For example, a `mod z { ... }` inside `x/y.rs` should set the current
+            // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`.
+            if let DirectoryOwnership::Owned { relative } = &mut self.directory.ownership {
+                if let Some(ident) = relative.take() { // remove the relative offset
+                    self.directory.path.to_mut().push(ident.as_str());
+                }
+            }
             self.directory.path.to_mut().push(&id.as_str());
         }
     }
diff --git a/src/test/ui/non_modrs_mods_and_inline_mods/non_modrs_mods_and_inline_mods.rs b/src/test/ui/non_modrs_mods_and_inline_mods/non_modrs_mods_and_inline_mods.rs
new file mode 100644
index 0000000000000..25a9c2ed98e04
--- /dev/null
+++ b/src/test/ui/non_modrs_mods_and_inline_mods/non_modrs_mods_and_inline_mods.rs
@@ -0,0 +1,5 @@
+// compile-pass
+
+mod x;
+
+fn main() {}
diff --git a/src/test/ui/non_modrs_mods_and_inline_mods/x.rs b/src/test/ui/non_modrs_mods_and_inline_mods/x.rs
new file mode 100644
index 0000000000000..a39a7c6d9b3ee
--- /dev/null
+++ b/src/test/ui/non_modrs_mods_and_inline_mods/x.rs
@@ -0,0 +1,5 @@
+// ignore-test: not a test
+
+pub mod y {
+    pub mod z;
+}
diff --git a/src/test/ui/non_modrs_mods_and_inline_mods/x/y/z/mod.rs b/src/test/ui/non_modrs_mods_and_inline_mods/x/y/z/mod.rs
new file mode 100644
index 0000000000000..e8442a47f2c77
--- /dev/null
+++ b/src/test/ui/non_modrs_mods_and_inline_mods/x/y/z/mod.rs
@@ -0,0 +1 @@
+// ignore-test: not a test