Search code examples
dockernginxsubdomain

How use nginx to create subdomains and map API to localhost:80?


I have a docker that run my api on localhost:80 and 2 folder for my fronts.

Here is what I want:

  • If I visit api.example.com map it to localhost:80
  • If I visit admin.example.com map it to folder ~/admin
  • If i visit example.com map it to folder ~/front

How can do this?


Solution

  • I found my answer and thanks from @Patrick-Mevzek.

    I solved my problem by adding below server blocks to my nginx configuration.

    server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        root         /home/erfantahvieh.com/front;
    
        server_name domain.example www.domain.example;                
    
        index index.html index.htm index.nginx-debian.html;
    
        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;
    
        location / {
             autoindex on;
             autoindex_exact_size off;
        }
    
        error_page 404 /404.html;
                location = /40x.html {
        }
    
        error_page 500 502 503 504 /50x.html;
                location = /50x.html {
        }
    }
    
    server {
        listen       80;
        root         /home/erfantahvieh.com/admin;
    
        server_name admin.domain.example www.admin.domain.example;                
    
        index index.html index.htm index.nginx-debian.html;
    
        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;
    
        location / {
        }
    
        error_page 404 /404.html;
                location = /40x.html {
        }
    
        error_page 500 502 503 504 /50x.html;
                location = /50x.html {
        }
    }
    
    server {
        listen       80;
        root         /usr/share/nginx/html;
    
        server_name api.domain.example www.api.domain.example;                
    
        index index.html index.htm index.nginx-debian.html;
    
        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;
    
        location / {
                proxy_pass http://xxx.xxx.xxx.xxx:8080/;
        }
    }