Search code examples
node.jsnginxsubdomaindigital-oceanubuntu-18.04

i need to setup my domain with nginx server for node.js project


i have already added CNAME & A Record in my server also i check with nginx command:

nginx -t

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

i write code for my domain example.co & www.example.co: /etc/nginx/sites-available/example.conf

server {
    listen 80;
    listen [::]:80;
    server_name example.co www.example.co;
    return 301 $scheme://www.example.co$request_uri;
}

server {
    listen 443 ssl http2 ;
    listen [::]:443 ssl http2 ;

    server_name example.co www.example.co;

    access_log /var/log/nginx/example-co.log;

    location / {
        proxy_pass "http://127.0.0.1:1000";
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }

    ssl_certificate /etc/letsencrypt/live/example.co/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.co/privkey.pem;
}

IP: 127.0.0.1:1000 node.js project for example.co my issue is example.co is working fine but www.example.co is not working

also i have write code for my domain sub1.example.co & www.sub1.example.co: /etc/nginx/sites-available/sub1-example.conf

server {
    listen 80;
    listen [::]:80;
    server_name sub1.example.co www.sub1.example.co;
    return 301 $scheme://www.example.co$request_uri;
}

server {
    listen 443 ssl http2 ;
    listen [::]:443 ssl http2 ;

    server_name sub1.example.co www.sub1.example.co;

    access_log /var/log/nginx/sub1-example-co.log;

    location / {
        proxy_pass "http://127.0.0.1:2000";
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }

    ssl_certificate /etc/letsencrypt/live/example.co/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.co/privkey.pem; # managed by Certbot
}

IP: 127.0.0.1:2000 node.js project for sub1.example.co,

my sub1.example.co is not working


Solution

  • You need to add www.example.co to your server block with 443:

    server {
        .....
         server_name example.co www.example.co;
        .....
    }
    

    For your subdomain, suggest to use another file for your server blocks configuration using the same format: one server block for 80 and another for 443. :)