6
votes

I am trying to create a nginx server that can host multiple sites on the same server. I have kept two different directories containing index.html files in the /var/www/ directory.

1st directory : dir1 Containing folder strucuture as : dir1/Folder/app; app directory contains index.html for the site.

2nd directory : dir2 Containing folder strucuture as : dir2/Folder/app; app directory contains index.html for the site.

now inside /etc/nginx/conf.d, created 2 .conf files as test.conf and dev.conf

test.conf :

server {
    listen 80 default_server;
    server_name mydomain.net;
    location /dir1/ {
        root /var/www/dir1/PharmacyAdminApp/app;
        index index.html index.htm;
        try_files $uri $uri/ =404;
    }
}

dev.conf

server {
    listen 80 default_server;
    server_name mydomain.net;
    location /dir2/ {
        root /var/www/dir2/PharmacyAdminApp1/app;
        index index.html index.htm;
        try_files $uri $uri/ =404;
    }
}

After this I restart the nginx server and visit "mydomain.net:80/dir1" on the browser but I get 404. Can anyone let me know what is the issue?

1
And if you try "mydomain.net:80/dir1/" in your browser? Same thing? (Notice the trailing slash in the URL) - Keenan Lawrence
Yes it happens the same for both dir1 and dir2. - Shiv Anand
Are you sure the config loaded? Try nginx -t. You have two identical server blocks (which is invalid). What you need is one server block containing the two location blocks. - Richard Smith
Also, you need to use alias and not root. - Richard Smith

1 Answers

9
votes

The above configuration should raise an error as you have defined two default_server, Also there is no point in defining two server blocks for the same domain,

This is how you can achieve it,

map $request_uri $rot {
    "~dir1" /var/www/dir1/Folder/app/;
    default /var/www/dir2/Folder/app/;
}
server {
    listen 80 default_server;
    server_name mydomain.net;
    root $rot;
    index index.html;

    location / {
        try_files $uri $uri/  index.html =404;
    }
}

The other way can be,

server {
    listen 80 default_server;
    server_name mydomain.net;

    location /dir2/ {
        root /var/www/dir2/PharmacyAdminApp1/app;
        index index.html index.htm;
        try_files $uri $uri/ /index.html =404;
    }
    location /dir1/ {
        root /var/www/dir1/PharmacyAdminApp1/app;
        index index.html index.htm;
        try_files $uri $uri/ /index.html =404;
    }
}

If it still throws any error, switch your error_log on, and check which files are being accessed, and correct from there.