Deploy the instance method of the react project on nginx

  • 2020-05-15 03:38:57
  • OfStack

Test item: react-demo

Clone your react-demo project to the server (Github is used by default to manage our project) If necessary, install the project environment, such as node.js, yarn, etc Go into the project directory, execute npm run build, and start building the project After a successful build, an dist folder (depending on your project configuration) will be generated. The static files in this folder are the access files of our project. Configure Nginx, Linux server is entered into: /etc/nginx/ sites-enabled, then as the administrator, create a new configuration file for your react project, such as: react-demo.conf, then edit the file:

server {
  listen 8080;
  # server_name your.domain.com;
  root /home/root/react-demo/dist;
  index index.html index.htm;
  location / {
    try_files $uri $uri/ /index.html;
  }
  location ^~ /assets/ {
    gzip_static on;
    expires max;
    add_header Cache-Control public;
  }
  error_page 500 502 503 504 /500.html;
  client_max_body_size 20M;
  keepalive_timeout 10;
}

Execute sudo service nginx restart to restart Nginx service,

Access project, http://IP:8080/

Matters needing attention:

1, the configuration of the domain name, need 80 port, after success, as long as the access to the domain name can access the project

2. If you are using React-Router browserHistory mode, please add the following configuration to the Nginx configuration:


location / {
  try_files $uri $uri/ /index.html;
}

Principle, because our project is only one root entry, when the input/home url similar, can not find the page, this is, can try to load index nginx html, loading index. After html react - router can play a role and match our input/home routing, so as to display the correct home page, and if there is no configuration browserHistory model of project the above content, there will be 404.

Please refer to the react-router documentation:

https://react-guide.github.io/react-router-cn/docs/guides/basics/Histories.html

conclusion


Related articles: