Domain and subdomain https from same Nginx

Hope this is not an ignorant question. I’ve tried to google for this, but cannot seem to find a solution that works for our use case, and I don’t want to goof up our production server. Thank you for your patience in helping point me in the right direction. (I’m not looking to be spoonfed, happy to do some reading on my own.)

Basically, we have our own example.com which points to /home/example inside Nginx conf file.

#---- PORT 80 http to always reroute to https version 
server {
        listen 107.170.3.157:80;
        server_name example.com ;
        return 301 https://example.com$request_uri;
}
    

#---- This is the main https block
server {
        listen 443        ssl http2 deferred;
        listen [::]:443   ssl http2 deferred;

        server_name   example.com;
        root /home/example;

        ssl_certificate           /etc/letsencrypt/live/example.com/fullchain.pem;
        ssl_certificate_key       /etc/letsencrypt/live/example.com/privkey.pem;#
...

But now, we want another subdomain on the same domain. So we want sub.example.com. Can we just create a main server block like the above, but pointing to the new folder /home/sub/?

#================== SUBDOMAIN FIRST ============
#---- PORT 80 http to always reroute to https version 
server {
        listen 107.170.3.157:80;
        server_name sub.example.com ;
        return 301 https://sub.example.com$request_uri;
}
    
#---- This is the main https block
server {
        listen 443        ssl http2 deferred;
        listen [::]:443   ssl http2 deferred;

        server_name   sub.example.com;
        root /home/sub;

        ssl_certificate           /etc/letsencrypt/live/example.com/fullchain.pem;
        ssl_certificate_key       /etc/letsencrypt/live/example.com/privkey.pem;#
...

    
#================== MAIN DOMAIN ============
#---- PORT 80 http to always reroute to https version 
server {
        listen 107.170.3.157:80;
        server_name example.com ;
        return 301 https://example.com$request_uri;
}
    

#---- This is the main https block
server {
        listen 443        ssl http2 deferred;
        listen [::]:443   ssl http2 deferred;

        server_name   example.com;
        root /home/example;

        ssl_certificate           /etc/letsencrypt/live/example.com/fullchain.pem;
        ssl_certificate_key       /etc/letsencrypt/live/example.com/privkey.pem;#
...

Is this the correct way to do this?

Thank you!

This looks like it should work. You can somewhat simplify the redirect by making a single HTTP block like so:

server_name example.com sub.example.com;
return 301 https://$server_name$request_uri;

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.