I have a root directory /var/www/html/
In above root directory I have multiple projects example project1
project2
I want to host two NextJs application in single file of nginx configuration.
Below is my nginx config file
location / {
root /var/www/html/project1/;
proxy_pass http://localhost: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;
proxy_hide_header Cache-Control;
add_header Cache-Control "no-cache, no-store";
}
location /_next/static/ {
alias /var/www/html/project1/.next/static/;
expires 365d;
access_log off;
}
location /blog/ {
rewrite /blog/(.*) /$1 break;
proxy_cache my_cache;
root /var/www/html/project2/;
proxy_pass http://localhost:3003/;
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;
proxy_hide_header Cache-Control;
add_header Cache-Control "no-cache, no-store";
}
location /blog/_next/static/ {
alias /var/www/html/project2/.next/static/;
expires 365d;
access_log off;
}
When I run the project2 i.e mydomain.com/blog
on production server, chunk is serving from root not from blog eg:
mydomain.com/_next/static/chunks/4574.41d99ce27dfde7f6.js
expected result – mydomain.com/blog/_next/static/chunks/4574.41d99ce27dfde7f6.js
2
Answers
It could be because of the way you are setting up the alias and the proxy_pass for the second application. In /blog/_next/static/ location, you are using the alias directiv. But for the /blog/ location you are using the root directive. I think probably this is causing the server to look for files in the wrong location, leading to incorrect URLs. You could use try_files directive in the /blog/ location to allow Nginx to serve static files from the expected location and routes the remaining requests to the appropriate proxy. Try something like this,
Try this
The key change here is in the location /blog/ block. The rewrite rule has been modified to remove the /blog/ prefix from the URI before passing it to the upstream server. This ensures that the URLs are correctly handled by the second Next.js application, and the chunks will be served from the expected /blog/_next/static/ directory.
After making this change, your NGINX configuration should serve the chunks from the correct subdirectories for both Next.js applications.