Skip to main content

Command Palette

Search for a command to run...

Configure Nginx for MERN GraphQL app on Digitalocean

Updated
1 min read
Configure Nginx for MERN GraphQL app on Digitalocean

You can configure Nginx for your MERN GraphQL app on the Digitalocean droplet and redirect www to the non-www domain over SSL. Copy and paste the following code in /etc/nginx/sites-available/domain.com.conf and then create a symbolic link to enable the new server block with the following command:

$ sudo ln -s /etc/nginx/sites-available/domain.com.conf /etc/nginx/sites-enabled/
server {
    listen 443 ssl http2;
    #Path to the React front end
    root /var/www/html/domain.com;

    #the main html file
    index index.html;

    #Enter the domain name
    server_name domain.com;

    #STORE the nginx access logs for this app here
    access_log /var/log/nginx/domain.com.access.log;
    #Store the error logs for this app here
    error_log /var/log/nginx/domain.com.error.log;

    ssl_certificate /etc/letsencrypt/live/domain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/domain.com/privkey.pem;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

    location / {
        # Without this line routing in your Single Page APP will not work  
        try_files $uri $uri/ /index.html =404;
    }

    #GRAPHQL BACKEND CONFIG
    location /api/ {
        proxy_pass https://localhost:6443/;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
    }

}
# redirect all https traffic from www to non-www
server {
    listen 443 ssl;
    server_name www.domain.com;
    return 301 https://domain.com$request_uri;

    #change this to your certificate paths 
    ssl_certificate /etc/letsencrypt/live/domain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/domain.com/privkey.pem;   
}
# redirect all traffic from http to https
server {
    listen 80;
    server_name domain.com www.domain.com;
    return 301 https://$host$request_uri;
}

More from this blog

R

Raja Muhammad Asher - Senior Software Engineer - Full Stack Developer

157 posts

Full Stack Developer with a passion for building web applications. PHP, Node.js, Laravel, ExpressJS, MySQL, MongoDB. Love collaborating & making a difference