Typical React applications face caching problems that can be solved using Nginx configuration
General deployment
Once you build your application, you simply point to static files using Nginx
server {
listen 80;
root /PATH/TO/APP/build;
try_files $uri $uri/ /index.html;
}
Copy the code
The cache problem
The first time a page is requested, all pages and resources are returned from the server, as shown below:
Close the browser, open it again, type the url, and press Enter. The browser will retrieve the file from the local cache, as shown below:
Even if the page is updated between requests, the browser does not retrieve the update from the server because the disk cache does not communicate with the server
solution
If a resource file is updated, its filename is updated, so caching of the resource is not an issue, just disable caching of the page
Namely put the above
try_files $uri $uri/ /index.html;
Copy the code
Replace with
location / {
if ( $uri = '/index.html' ) {
add_header Cache-Control no-store always;
}
try_files $uri $uri/ /index.html;
}
Copy the code
- Because all pages end up pointing to the entry file, the actual
$uri
Are all/index.html
no-store
Is the strictestCache-Control
Disable cached values to ensure that the browser does not use any caching- because
add_header
Jointly and severallyif
Not directly in theserver
So I added a layer of location
To solve the effect
The second time the page is requested, the page itself will not be cached, but the resource will be cached if it has not changed, as shown below:
You can access the following addresses, try the operation, and view the corresponding network request:
react.chanvinxiao.com
conclusion
- A strange cache problem occurs when the browser types the address and presses Enter
- Through Nginx
$uri
You can determine if the request is a page - Through Nginx
add_header
The cache control header can be set