Gorgsenegger
Gorgsenegger

Reputation: 7856

nginx serving files from two different directories on one server

I have the following directory structure in my web server's filesystem:

-srv
 +---someDir
 |   +---mySite
 +---someOtherDir
     +---yourSite

Both, mySite and yourSite, shall be available from the same nginx webserver under different directories (path in the browser address bar), such as

http://myServer/mySite and

http://myServer/yourSite

I've tried to have one server entry in the configuration with two location blocks (with varying settings), but none delivered the expected result - neither with a "server level" root entry, not without. For example (nginx.conf):

http {
    ...
    server {
        root /srv/;
        location = /mySite {
            root /srv/someDir/mySite/;
    }
}

As I said, all with different combinations of root and also try_files etc.

I thought it should be possible to have something like

...
server {
    location = /mySite {
        root /srv/someDir/mySite/;
    }

    location = /yourSite {
        root /srv/someDir/yourSite/;
    }
}

Where is my error?

Upvotes: 1

Views: 734

Answers (1)

Richard Smith
Richard Smith

Reputation: 49672

The simplest solution is where you have total control over the filesystem and URI name spaces, so that the application in /path/to/root/foo/index.html is accessible using the URI /foo/ and the application in /path/to/root/bar/index.html is accessible using the URI /bar/.

In this case, no location blocks are necessary, and the value of root is /path/to/root because the pathname of the file is constructed by concatenating this value with the URI. See this document for details.

For example:

server {
    server_name example.com;
    root /path/to/root;
}

The above server block will fine application foo at http://example.com/foo/ and application bar at http://example.com/bar/.


In the case where the top level directory element has a different name to the top level URI element, you will need to use an alias directive within a location block. See this document for details.

For example:

server {
    server_name example.com;

    location /foo/ {
        alias /path/to/foos/directory/;
    }
    location /bar/ {
        alias /path/to/bars/directory/;
    }
}

Both the location value and the alias value should end with /, or neither end with /.

Note that the location directive is used without the = operator, which is only used to match a single URI. See this document for details.

Upvotes: 1

Related Questions