nginx - location 配置,最长匹配
Add the following location
block to the server
block:
location / { root /data/www; }
This location
block specifies the “/
” prefix compared with the URI from the request. For matching requests, the URI will be added to the path specified in the root directive, that is, to /data/www
, to form the path to the requested file on the local file system. If there are several matching location
blocks nginx selects the one with the longest prefix. The location
block above provides the shortest prefix, of length one, and so only if all other location
blocks fail to provide a match, this block will be used.
Next, add the second location
block:
location /images/ { root /data; }
It will be a match for requests starting with /images/
(location /
also matches such requests, but has shorter prefix).
The resulting configuration of the server
block should look like this:
server { location / { root /data/www; } location /images/ { root /data; } }
This is already a working configuration of a server that listens on the standard port 80 and is accessible on the local machine at http://localhost/
. In response to requests with URIs starting with /images/
, the server will send files from the /data/images
directory. For example, in response to the http://localhost/images/example.png
request nginx will send the /data/images/example.png
file. If such file does not exist, nginx will send a response indicating the 404 error. Requests with URIs not starting with /images/
will be mapped onto the /data/www
directory. For example, in response to the http://localhost/some/example.html
request nginx will send the /data/www/some/example.html
file.
To apply the new configuration, start nginx if it is not yet started or send the reload
signal to the nginx’s master process, by executing:
nginx -s reload
In case something does not work as expected, you may try to find out the reason inaccess.log
anderror.log
files in the directory/usr/local/nginx/logs
or/var/log/nginx
.
测试不同的location:
测试3: