Nginx 404 on static files (react application) - reactjs

I tried to setup a React application on nginx, but I faced a problem when serving static files from a subdirectory
My file tree is like this :
/var/www/
antoinedeveyrac.io/
...
react/
...
build/
index.html
static/
js
*.js
css
*.css
My conf file is :
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
include snippets/ssl-antoinedeveyrac.io.conf;
include snippets/ssl-params.conf;
root /var/www/antoinedeveyrac.io/html;
index index.html index.htm index.nginx-debian.html;
server_name antoinedeveyrac.io www.antoinedeveyrac.io;
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
try_files $uri $uri/ =404;
}
location ~ /.well-known {
allow all;
}
location /react {
alias /var/www/react/build;
try_files $uri $uri/ =404;
autoindex off;
index index.html;
}
}
So when I am hitting https://antoinedeveyrac.io/react, I have those 404 errors, which means nginx doesn't understand that I want to serve file from https://antoinedeveyrac.io/react/static/... instead of https://antoinedeveyrac.io/static/...
How can I fix my config file to match my static files inside a subdirectory ? Thanks a lot :)

Are you getting 404's on the assets being referenced in /var/www/react/build/index.html, or on the index.html page itself? I would ask this in a comment, but rep is not high enough yet.
Your nginx root config is pointing to an html directory which doesn't appear to exist, based on the directory output you posted.
root /var/www/antoinedeveyrac.io/html;
Try changing the root config to ...
root /var/www/antoinedeveyrac.io/
In your index.html, you should reference assets like this(if you are not doing already)
<link href="scripts/somefile.css" rel="stylesheet">

Related

Redirect root to /path/ for single page application and NGINX

What I'm trying to achieve is to have a project use the subdomain as part of the request path for react SPA.
e.g. qem.xxx.com -> xxx.com/qem for a SPA where the file path doesn't change with the request.
I've been messing about for a while with rewrites but haven't been able to achieve it. Most of the resources seem to deal with the opposite, or with non-SPAs where the file path matches.
Here's the latest conf:
server {
listen ${NGINX_PORT};
server_name ${NGINX_HOST}
charset utf-8;
client_max_body_size 20M;
# what file to server as index
root /src/build;
index index.html index.htm;
error_page 503 #maintenance;
location #maintenance {
root /src;
rewrite ^(.*)$ /deploy/maintenance.html break;
}
location / {
# First attempt to serve request as file, then
# as directory, then fall back to redirecting to index.html
if (-f /src/maintenance.txt) {
return 503;
}
try_files $uri $uri/ #qem /index.html;
}
location #qem {
rewrite ^ /qem/$request_uri?;
try_files $uri $uri/ /index.html;
}
}
EDIT: Further details as requested:
NGINX_HOST=qem.xxx.com
Only one SPA application, so only one index.html in folder root
Have static resources that $uri and $uri/ match, all site content is served by index.html
Trying to achieve access to qem.xxx.com to serve as if the user accessed xxx.com/qem/ (i.e. this subdomain serves that part of SPA)
Currently semi-works in that it serves a blank page (200s).
Even just a general steer in the correct direction would be great!
Cheers,
Carl

Why is my nginx routing my react app static files to my index.html

I want to host a demo app on a subroute of my domain. When I place the app in the root of the domain and use the following configuration, it works:
server {
server_name domain.com www.domain.com;
root /var/www/my-app/build;
index index.html index.htm;
location / {
try_files $uri /index.html =404;
}
}
But when i move it to a subroute using the following configuration, it correctly fetches the initial index.html but then routes the static file requests (for css, js, images...) to index.html as well.
server {
listen 80;
server_name domain.com www.domain.com;
location / {
}
location /demo-apps/my-app{
root /var/www/my-app/build;
try_files $uri /index.html =404;
}
}
And I don't understand why. Here's a screen capture of the request which succeeds but returns the index.html file instad of the js file:
And here's the folder structure on the server:
As I understand it, the request from the first screen capture should match the $uri condition in the second location block and return the corresponding js file but, clearly, I'm wrong. What do I need to change for this to work?
Before anyone asks, yes, I did restart nginx.
The path to the file is constructed by concatenating the value of root with the value of $uri. So a request for /demo-apps/my-app/css/foo.css will be looked for at /var/www/my-app/build/demo-apps/my-app/css/foo.css, which is the wrong place.
You can use alias instead (see this document), for example:
location /demo-apps/my-app {
alias /var/www/my-app/build;
try_files $uri /demo-apps/my-app/index.html;
}
However, using alias and try_files together can be problematic. See this long term issue.
Or use a regular expression location (see this dcoument) to extract the latter part of the URI, for example:
location ~ ^/demo-apps/my-app(/.*)?$ {
root /var/www/my-app/build;
try_files $1 /index.html =404;
}

Nginx Subfolder admin react app under main react app

I have a situation where i have two apps developed in react.
User App
Admin App
I made a build of both apps and have placed the user app build in site directory, where as admin app build is inside site/admin directory
What i want is
when someone tries www.mydomain.com/admin, it should go to admin directory, where as if no admin is given in url then it should not look for admin instead user files should be served.
I am willing to change directory structure any possible way to make this urls work as expected.
I have given alot of time and tries but failed to achieve the result. I am missing something, possibly its related to try_files configuration but i am not sure yet.
Following is the Nginx file i have created so far for my needs.
If i write mydomain.org/admin, it works fine.
But when i write mydomain.org/admin/{someotherparam e-g dashboard}, it loads the main user react app instead of admin app. I guess it reads the index file of user in that case. How to make read the index file of admin if /admin/ is in the url on first.
I have not much knowledge on nginx configuration, thou i did tried google.
Only 1 task is remaining to do on my part is if i put admin directory and user directory separate.
But then i would have to do domain.org/user and domain.org/admin, which i do not want.
I want admin react to work only if there is admin in url in first place after url.
I am not sure how to get this to working.
server {
listen 80;
listen [::]:80;
# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html;
server_name mydomain.org www.mydomain.org;
location / {
root /var/www/mydomain.org/html/frontend/site;
try_files $uri $uri/ /index.html;
}
location /admin(.*) {
root /var/www/mydomain.org/html/frontend/site/admin;
try_files $uri $uri/ /index.html;
}
}
I am using LEMP on ubuntu 18.
Could you try this config?
server {
listen 80;
listen [::]:80;
# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html;
server_name mydomain.org www.mydomain.org;
root /var/www/mydomain.org/html/frontend/site;
location / {
try_files $uri $uri/ /index.html;
}
location /admin {
try_files $uri $uri/ /admin/index.html;
}
}

How configure nginx for prerender React App?

I've got React app.
It works well on local machine (app + prerender-spa-plugin). I run it with command http-server into ./build package
However thing go wrong on server - it acts like if I launch it with serve-s command.
There is docker with nginx image on server.
I tried to reconfigure nginx the way that it uses different index.html for different URLs, but fail again
Do the problem with routing to directories that keeps static images?
How it could be resolved? or where I could find information about it?
You have to create virtual host on nginx server and point it to build folder of the app. Don't forget to run npm run build.
Simple nginx config
server {
listen 80;
listen [::]:80;
root /var/www/reactjsapp/build;
index index.html index.htm;
server_name reactjsapp.com;
location / {
try_files $uri /index.html;
}
location ~ /\.ht {
deny all;
}
}
I decided it.
My config
location / {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
From official documentation:"It is possible to check directory’s existence by specifying a slash at the end of a name, e.g. “$uri/”."
https://i.stack.imgur.com/PusBE.png

Deploy Laravel and React spa

How can I deploy these two together, I don't like the Laravel React preset, I want to separate both, bundle the React app and deploy them together with any web server (apache, nginx...)
EDIT
This is my config for Laravel, but it isn't loading the routes
server {
listen 8000;
server_name 127.0.0.1
root "..\..\Proyecto\Backend\JWT\public";
add_header 'Access-Control-Allow-Origin' '*';
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";
index index.html index.htm index.php;
charset utf-8;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt { access_log off; log_not_found off; }
error_page 404 /index.php;
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
include fastcgi_params;
}
location ~ /\.(?!well-known).* {
deny all;
}
}
You can run them separately using nginx
you run each on separate ports and use methods (POST/GET) to push/get data
use pm2 (http://pm2.keymetrics.io/) for running React (I recommend it because you can monitor the activity of the react app and if you want to do maintenance you can stop the current app process and run a "under maintenance" app process)
you can read more about running laravel on nginx here (https://www.digitalocean.com/community/tutorials/how-to-deploy-a-laravel-application-with-nginx-on-ubuntu-16-04)
as for running react without pm2, you have to build the project yarn build and tell nginx that the file you want to load is the index.html inside of the build file
assuming that you are using an ubuntu server and you uploaded your code to github or gitlab
server {
listen 50;
root /var/www/[Your repo name]/build;
server_name [your.domain.com] [your other domain if you want to];
index index.html;
location / {
try_files $uri /index.html;
}
}
you write this inside of your nginx configuration along with the laravel configuration on a separate port
hope my answer helped a bit
This was proving to be very tricky and it took me at least 3 days to put everything together. Here is what you have to do.
Run
npm run build in the react project.
Copy the contents of the build folder to the server
scp react_project/build/* <server name or ip>:/var/www/html/react
Change the ownership of the project folders to the user www-data or add your user id to the group www-data.
Now. set up the Laravel project in a different directory (in /var/www/html/laravel, for example).
Set up the database, environment variables.
Run
php artisan key:generate
php artisan config:clear
php artisan config:cache
Now, proceed with nginx configuration. Create 2 configs for react and laravel projects as given below. Make sure that the listen ports are different for both projects.
Create configuration files for react and laravel projects under /etc/nginx/sites-available
Create symlinks to the created configs under /etc/nginx/sites-enabled as given below
sudo ln -s /etc/nginx/sites-available/react_conf /etc/nginx/sites-enabled/react_conf
sudo ln -s /etc/nginx/sites-available/laravel_conf /etc/nginx/sites-enabled/laravel_conf
And for the contents,
react_conf:
server {
listen 80;
server_name <server_ip or hostname>;
charset utf-8;
root /var/www/html/react;
index index.html index.htm;
# Always serve index.html for any request
location / {
root /var/www/html/react;
try_files $uri /index.html;
}
error_log /var/log/nginx/react-app-error.log;
access_log /var/log/nginx/react-app-access.log;
}
laravel_conf:
server {
listen 90;
server_name <server ip or hostname>;
charset utf-8;
root /var/www/html/laravel/public;
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";
index index.php index.html index.htm;
# Always serve index.html for any request
location /api {
try_files $uri $uri/ /index.php?$query_string;
}
location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt { access_log off; log_not_found off; }
error_page 404 /index.php;
location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
include fastcgi_params;
}
location ~ /\.(?!well-known).* {
deny all;
}
error_log /var/log/nginx/laravel-app-error.log;
access_log /var/log/nginx/laravel-app-access.log;
}
Now, delete the default config present in /etc/nginx/sites-enabled
Also, verify that /etc/nginx/nginx.conf contains the following include directive where the server configs are expected(under http)
include /etc/nginx/sites-enabled/*;
Verify that the config is fine by running
sudo nginx -t
Restart the server
sudo service nginx restart
Now, you should be up and running.
You can approach it by two ways .
First one is when the you are creating react-app in different folder than the laravel project folder . In such case just deploy laravel app and react app in two different url .
The second condition is when the react-app is inside the laravel app . In such case build the react project and put the dist folder in views folder of the laravel project . So in routes/web.php add this
//Used for handling the html file of react project
View::addExtension('html', 'php');
Route::get('/{any}', function () {
//path to dist folder index.html inside the views directory
return view('build/index');
})->where('any', '.*');
Laravel will not server the required js and css file from inside the views folder . So you need copy and paste all the content of the dist folder to public folder of the laravel project . No need to copy paste index.html file but other file need to placed in the pubic folder .
After that visit the root url of the laravel project in the browser the react app should be working

Resources