Digital Ocean IP - Redirect to Domain Name and Protect your app

Posted 4 years ago by Ryan Dhungel

Category: Next JS Digital Ocean Node

Viewed 7573 times

Estimated read time: 2 minutes

When you push your app to digital ocean droplet, they are accessible using IP address which will look something like this 123.345.567.899

Hoever you may want to remove the ability to access your app using IP once you have added a domain name to your app. Well the code below will help you do just that. Just replace the domain name with your actual domain name.

Configure nginx

cd /etc/nginx/sites-available
sudo vim default

Add additional server block in file - default

server {
    listen 80;
    server_name 123.456.789.999;

    return 301 $scheme://$request_uri;

Restart nginx once you have made the change

sudo systemctl restart nginx

Protect your app 

I had a situation where my app was also served under someone else's domain name. Probably the guy had his domain pointed to my IP for whatever reason. So I added this little code snippet as middleware to my server.js. I am basically checking if the domain name match the hostname then of course that is my domain so no problem. Otherwise if anyone else is showing your app in their domain or sub-domain you will redirect back to your domain. Problem solved.


// next js server.js
if (process.env.NODE_ENV === 'production') {
    server.get('*', (req, res, next) => {
        let hostname = req.hostname;
        if (hostname.includes('domain_name')) {
            console.log('yes includes my domain name in ', hostname);
        } else {
            res.redirect(301, '');
            console.log('no dont includes domain_name in ', hostname);