This is the second day of my participation in Gwen Challenge

This article introduces how to configure a single page application using Nginx based on engineering practice.

Problem 1.

The initial configuration of the static resource mapping in nginx.conf is as follows:

root /usr/share/nginx/html/appname/;
index index.html index.htm;
Copy the code

The above configuration allows normal access to index.html, and can be clicked sequentially to go to other pages. But the browserHistory and Refresh pages of the browser report 404.

Reason 2.

Because we deploy single-page applications, the current mainstream front-end frameworks are single-page, such as React and Vue.

A single page simply means access to all of the resource paths, but there is only one page content (usually index.html). The JS framework introduced in this page will route the currently visited URL to the corresponding sub-page components (which can be understood as page fragments) for logical processing and page rendering.

So we directly access a page resource (such as /usr/info) that doesn’t exist, so the server will report 404.

3. Solutions

root /usr/share/nginx/html/appname/;
index index.html index.htm;
location / {
         try_files $uri $uri/ /index.html;
}
Copy the code

When try_files fails to find a page resource, nginx will try to load index.html. After loading index.html, the react-router will work and match the /home route we entered to display the correct home page.

4. Complete the configuration

Complete configuration, for reference only.

access_log /var/log/nginx/access.log;
	error_log /var/log/nginx/error.log;
	server {
		listen 80;
		# gzip config
		gzip on;
		gzip_min_length 1k;
		gzip_comp_level 9;
		gzip_types text/plain text/css text/javascript application/json application/javascript              application/x-javascript application/xml;
		gzip_vary on;
		gzip_disable "MSIE [1-6]\.";
		root /usr/share/nginx/html/appname/;
		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;
	}
Copy the code