next.js application nginx not loading css and js. Runs perfectly when specify port (3000)

Viewed 1600

i have deployed a nextjs app on AWS ec2 instance running ubuntu and nginx

using pm2 to run nextjs

the proxy pass entry in nginx conf is like

location / {
        # reverse proxy for next server
        proxy_pass http://127.0.0.1:3000;
        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;

        include  /etc/nginx/mime.types;
        # we need to remove this 404 handling
        # because next's _next folder and own handling
        # try_files $uri $uri/ =404;
    }

My problem is that when I specify port in the ip like http://10.20.30.40:3000 my site comes up properly with all css and javascript loaded

but when no port is specified like http://10.20.30.40 my css and javascript are not loaded and I can see only text

What is wrong? Any help will be highly appreciated. Thanks

1 Answers

I think you need to serve the static assets from the Nginx.

/etc/nginx/sites-available/default

Add the below code in your server config file /etc/nginx/sites-available/default

location /_next/static {
    alias /home/ubuntu/PROJECT_FOLDER/.next/static;
    add_header Cache-Control "public, max-age=3600, immutable";
}

Full reference: https://gist.github.com/iam-hussain/2ecdb934a7362e979e3aa5a92b181153

Related