The nginx configuration of scenario is useful for front end development

  • 2020-05-09 19:52:39
  • OfStack

In front end work, local development, test environment, there must be a handy server software, nginx is very popular in this scenario.

Describes two useful configuration items: rewrite try_files@xxxx

rewrite

More commonly used to replace a static file path with a version number with a local file path

Such as renren release file path contains a a0000 version number, through the following configuration will http: / / xnimg cn a0001 / js/base js into http: / / xnimg cn/js/base js mapped directly to the local directory structure.


rewrite "^/a?([0-9]+)/(.*)" /$2 last;

try_files

Try to find the required file in multiple local paths and return 404 if it is still not found. Here's a more convenient feature with the @xxx configuration.

location @xxx

This defines a "request handling method" (handler) that can be called by another configuration, in combination with try_files, to automatically fetch the specified file online if no local file is found.


if ( $document_uri ~*"^/[ab]?([0-9]+)/(.*)"){
  set $no_version_path /$2;
}

location / {
  try_files $document_uri $no_version_path =404;
  error_page 404 = @online;
  log_not_found off;
}

location @online{
  proxy_pass http://$host:80/$request_uri
}

The first if statement is a match. Save the second group value (the path with the version number removed) of $2 to the variable $no_version_path.

Order of try_files: path with version number, path without version number, if 404 calls @online;

At @online, the two nginx variables $host and $request_uri spell out the file path of the request and directly proxy the request to the line.

This configuration of the server, you only need to store a few static files you care about in the local, other files do not need to debug all proxy to the online, save time every time you do not care about the update of the project code.


Related articles: