How can I set up sub-domains in Nginx?

Things I have set-up already"

  • Nginx running a Ruby rack app

  • DNS set-up with DigitalOcean

How do I create a sub-domain to root to another ruby app?

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

×
2 answers

To do this you would:

1.) Create an A record on your existing domain in the DNS system for your new subdomain and point it to your droplet’s IP.

2.) Create a second (non-default) server {} block in your nginx configuration pointing to your second app.

3.) Restart nginx with the command:

service nginx restart

Very simple steps

  1. Create a folder “sub.example.com” in /var/www/html/

  2. Create a config file “sub.example.com” in etc/nginx/site-availabe

    server {
        listen 80;
        listen [::]:80;
    
        root /var/www/html/sub.example.com;
        index index.php index.html index.htm index.nginx-debian.html; 
    
        server_name sub.example.com www.sub.example.com;
    
        location / {
                try_files $uri $uri/ =404;
        }
        location ~ \.php$ {
            #NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
            include fastcgi_params;                
            fastcgi_intercept_errors on;
            fastcgi_pass unix:/run/php/php7.2-fpm.sock;
            fastcgi_param SCRIPT_FILENAME 
                    $document_root/$fastcgi_script_name;
        }
    }
    

    Note php7.2-fpm may be change by your using php version

  3. Run

    ln -s /etc/nginx/sites-available/sub.example.com /etc/nginx/sites-enabled/sub.example.com
    
  4. Test configuration sudo nginx -t

  5. Restart the Nginx server:

    sudo systemctl restart nginx
    
Submit an Answer