nginx - location 配置,最長匹配
Add the followinglocation
block to theserver
block:
location / { root /data/www; }
Thislocation
block specifies the “/
” prefix compared with the URI from the request. For matching requests, the URI will be added to the path specified in therootdirective, that is, to/data/www
, to form the path to the requested file on the local file system. If there are several matchinglocation
location
block above provides the shortest prefix, of length one, and so only if all otherlocation
blocks fail to provide a match, this block will be used.
Next, add the secondlocation
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 theserver
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 athttp://localhost/
/images/
, the server will send files from the/data/images
directory. For example, in response to thehttp://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 thehttp://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 thereload
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
.