diff --git a/main.c b/main.c
index 7cd27f9abd0e7a117596540514491e0f85d60088..8aec5c1e0b152b7c0f9b491d8f397ce8f83fe13e 100644
--- a/main.c
+++ b/main.c
@@ -26,6 +26,7 @@
 #define _CRT_SECURE_NO_WARNINGS	/* Disable deprecation warning in VS2005 */
 #endif /* _WIN32 */
 
+#include <sys/stat.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <signal.h>
@@ -117,6 +118,23 @@ static void show_usage_and_exit(void) {
   exit(EXIT_FAILURE);
 }
 
+static void verify_document_root(const char *root) {
+  const char *p, *path;
+  char buf[PATH_MAX];
+  struct stat st;
+
+  path = root;
+  if ((p = strchr(root, ',')) != NULL && (size_t) (p - root) < sizeof(buf)) {
+    strncpy(buf, root, p - root);
+    path = buf;
+  }
+
+  if (stat(path, &st) != 0) {
+    fprintf(stderr, "Invalid root directory: \"%s\"\n", root);
+    exit(EXIT_FAILURE);
+  }
+}
+
 static char *sdup(const char *str) {
   char *p;
   if ((p = malloc(strlen(str) + 1)) != NULL) {
@@ -128,6 +146,10 @@ static char *sdup(const char *str) {
 static void set_option(char **options, const char *name, const char *value) {
   int i;
 
+  if (!strcmp(name, "document_root")) {
+    verify_document_root(value);
+  }
+
   for (i = 0; i < MAX_OPTIONS - 3; i++) {
     if (options[i] == NULL) {
       options[i] = sdup(name);
diff --git a/mongoose.c b/mongoose.c
index da04c33f46561d1ee23465c1deed824ea425cb22..6b0be233d5e136b0b5c7bcf2889b2ccc7b66a01b 100644
--- a/mongoose.c
+++ b/mongoose.c
@@ -3459,24 +3459,6 @@ static int set_acl_option(struct mg_context *ctx) {
   return check_acl(ctx, &fake);
 }
 
-static int verify_document_root(struct mg_context *ctx) {
-  char path[PATH_MAX], *p;
-  struct mgstat buf;
-  const char *root = ctx->config[DOCUMENT_ROOT];
-
-  if ((p = strchr(root, ',')) == NULL) {
-    mg_strlcpy(path, root, sizeof(path));
-  } else {
-    mg_strlcpy(path, root, p - root + 1);
-  }
-
-  if (mg_stat(path, &buf) != 0) {
-    cry(fc(ctx), "Invalid root directory: \"%s\"", root);
-    return 0;
-  }
-  return 1;
-}
-
 static void reset_per_request_attributes(struct mg_connection *conn) {
   if (conn->request_info.remote_user != NULL) {
     free((void *) conn->request_info.remote_user);
@@ -3830,11 +3812,6 @@ struct mg_context *mg_start(mg_callback_t user_callback, const char **options) {
     DEBUG_TRACE(("[%s] -> [%s]", name, value));
   }
 
-  if (!verify_document_root(ctx)) {
-    free_context(ctx);
-    return NULL;
-  }
-
   // NOTE(lsm): order is important here. SSL certificates must
   // be initialized before listening ports. UID must be set last.
   if (!set_ssl_option(ctx) ||