Home > front end >  How to use nginx for nuxt js as proxy and http server?
How to use nginx for nuxt js as proxy and http server?

Time:02-06

I have a NUXT js application on Ubuntu 20.04 Server. I used Nginx to serve my nuxt application as follow:

server {
client_max_body_size 300M;

root /var/www/app/dist;

server_name example.com;

location / {
        proxy_pass http://localhost:8080;
        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;
}

My NUXT application works with npm on port 8080 and Nginx reverse proxy, passes user requests to localhost:8080 and everything is working fine.

Now I want to access the js service worker file (named: p-sw.js). but when I try to access it via my website address, (https://example.com/p-sw.js) due to Nginx reverse proxy it returns 404. This file is in the dist folder (see Nginx configuration).

Anybody can explain to me how to set Nginx reverse proxy to works fine as before alongside load service worker file when I enter service worker address (https://example.com/p-sw.js) in browser?

CodePudding user response:

Finally, I solved it!

the Nginx config must look like this:

upstream backend {
    server localhost:3000;
}

server {
    server_name example.com;
    client_max_body_size 300M;
    root /var/www/app/dist;

    location /p-sw.js {
        try_files $uri @backend;
        add_header 'Cache-Control' 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
        expires off;
        proxy_no_cache 1;
    }

    location @backend {
        proxy_pass http://backend;
        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;
    }
}

In this configuration, I solved the issue by defining the location /p-sw.js for my service worker file, and for Nuxt routes, I used the same proxy pass!

  •  Tags:  
  • Related