0

I want to configure Nginx for routing multiple projects on localhost without touching hosts file on my computer.

I.e. Nginx should handle at least to paths

  1. http://localhost/project-one

  2. http://localhost/project-two

I found one example but it doesn't work in my case:

# /etc/nginx/conf.ddefault.conf
server {
    listen       80;
    # server_name  localhost;
    index  index.html index.htm;

    location ~ ^/project-one {
        root   /usr/share/nginx/html/project-one;
        # index  index.html index.htm;
    }

    location ~ ^/project-two {
        root   /usr/share/nginx/html/project-two;
        # index  index.html index.htm;
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

It works if I set just one location to just a slash and required root:

# /etc/nginx/conf.ddefault.conf
server {
    listen       80;
    # server_name  localhost;
    index  index.html index.htm;

    location / {
        root   /usr/share/nginx/html/project-one;
        # index  index.html index.htm;
    }
}

With this config it shows html file from project-one directory on http://localhost.

I am using Docker for testing:

docker run --rm --name my-nginx -p 80:80 -v $(pwd)/sites:/etc/nginx/conf.d -v $(pwd)/html:/usr/share/nginx/html -d nginx

So I can change default.conf file for Nginx and html folder in local directories respectively and then restart: docker restart my-nginx

How to configure more than one location properly for multiple roots without touching hosts file?

mr.boris
  • 3,667
  • 8
  • 37
  • 70
  • 1
    The value of `root` is concatenated with the URI to form the path to the file. The value should be `/usr/share/nginx/html` as the `project-one` and `project-two` are part of the URI. See [this document](http://nginx.org/en/docs/http/ngx_http_core_module.html#root) for details. – Richard Smith Apr 13 '20 at 15:46
  • @RichardSmith, thank you so much, it was pretty overwhelming for me until you shared this clear example with root. Thanks! – mr.boris Apr 13 '20 at 15:58

1 Answers1

3

Ok, finally I got it...

server {
    listen       80;
    # server_name  localhost;
    index  index.html index.htm;

    location ~ ^/project-one {
        root   /usr/share/nginx/html;
        # index  index.html index.htm;
    }

    location ~ ^/project-two {
        root   /usr/share/nginx/html;
        # index  index.html index.htm;
    }
}

And now it works as I expected:

http://localhost/project-one

http://localhost/project-two

Each request routes to the different folder relatively:

/usr/share/nginx/html/project-one/index.html

/usr/share/nginx/html/project-two/index.html

Thanks to @RichardSmith.

halfer
  • 19,824
  • 17
  • 99
  • 186
mr.boris
  • 3,667
  • 8
  • 37
  • 70