1. 程式人生 > 其它 >nginx - location 配置,最長匹配

nginx - location 配置,最長匹配

Add the followinglocationblock to theserverblock:

location / {
    root /data/www;
}

Thislocationblock 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

blocks nginx selects the one with the longest prefix. Thelocationblock above provides the shortest prefix, of length one, and so only if all otherlocationblocks fail to provide a match, this block will be used.

Next, add the secondlocationblock:

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 theserverblock 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/

. In response to requests with URIs starting with/images/, the server will send files from the/data/imagesdirectory. For example, in response to thehttp://localhost/images/example.pngrequest nginx will send the/data/images/example.pngfile. 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/wwwdirectory. For example, in response to thehttp://localhost/some/example.htmlrequest nginx will send the/data/www/some/example.htmlfile.

To apply the new configuration, start nginx if it is not yet started or send thereloadsignal 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.loganderror.logfiles in the directory/usr/local/nginx/logsor/var/log/nginx.

測試不同的location: