I recently helped a colleague solve a minor problem with nginx static resource configuration. Although very small, but still pondering for a long time, not Nginx pit me, is I too dish. Ha ha, I still want to record this little knowledge, later encountered the same problem can improve efficiency.

First, look at small needs

The requirement is simple, roughly: a url prefixed with /res indicates that the request is a static resource request and redirects it to the static resource path to get the static resource.

Here’s an example:

When the access path is: http://127.0.0.1:8080/res/. JPG, nginx should return to the beautiful scenery photo at this time.

Nginx configuration

This is a very simple requirement. The configuration using nginx is as follows:

location /res/ {
    root   f:/res/; 
}
Copy the code

When the /res/ prefix is matched, access the static resource files in the f:/res/ directory. The picture “scene.jpg” is stored in f:/res/.

After starting nginx, the following request displays 404

http://localhost/res/ scenery. JPG

F :/res/res/ landscape. JPG file/f:/res/res/

Now let’s change the above nginx configuration to:

location /res/ {
    alias   f:/res/; 
}
Copy the code

After starting nginx, I found the following request to display the image properly.

http://localhost/res/ scenery. JPG

If f:/res/ has this image, nginx will not report 404.

Third, the conclusion

The difference between the alias and root directives is:

  • F :/res/res/ XXX f:/res/ XXX f:/res/ XXX

  • 2. Alias removes the path configured for location

The request to http://localhost/res/xxx ignores the localhost configuration. It is not appended to the alias configuration path and becomes f:/res/ XXX. The /res/ of location is ignored.

Finally, do not access the Chinese name request on postman, such as http://localhost/res/ scenery. JPG, because Postman does not support Chinese, will always display 404, otherwise you will say why clearly configured in Postman is not effective, haha, finally doubt life.