我们有下面的虚拟服务器设置。 我们希望在访问/doc/ ,nginx会自动访问/doc/index.html ,并使用静态文件/data/doc/site/index.html来提供服务。
server { listen 8123 default_server; access_log /var/log/nginx/test.access.log; error_log /var/log/nginx/test.error.log; # Make site accessible from http://localhost/ server_name localhost; location /doc { root /data/doc/site; index index.html; rewrite /doc(.*) $1 break; } location / { proxy_pass_header Server; proxy_pass http://127.0.0.1:7001; // !!!not exists!!! } }
但,
$ curl http://192.168.1.230:8123/doc/ -v * Trying 192.168.1.230... * Connected to 192.168.1.230 (192.168.1.230) port 8123 (#0) > GET /doc/ HTTP/1.1 > Host: 192.168.1.230:8123 > User-Agent: curl/7.43.0 > Accept: */* > < HTTP/1.1 502 Bad Gateway < Server: nginx/1.4.6 (Ubuntu) < Date: Mon, 21 Dec 2015 07:37:29 GMT < Content-Type: text/html < Content-Length: 181 < Connection: keep-alive <
和
$ curl http://192.168.1.230:8123/doc/index.html -v * Trying 192.168.1.230... * Connected to 192.168.1.230 (192.168.1.230) port 8123 (#0) > GET /doc/index.html HTTP/1.1 > Host: 192.168.1.230:8123 > User-Agent: curl/7.43.0 > Accept: */* > < HTTP/1.1 200 OK < Server: nginx/1.4.6 (Ubuntu) < Date: Mon, 21 Dec 2015 07:33:47 GMT < Content-Type: text/html < Content-Length: 11 < Last-Modified: Mon, 21 Dec 2015 06:51:07 GMT < Connection: keep-alive < ETag: "5677a15b-b" < Accept-Ranges: bytes < root index
重写后,似乎nginx重新匹配一个新位置的变化的URL。 但在文件中,它说
last stops processing the current set of ngx_http_rewrite_module directives and starts a search for a new location matching the changed URI; break stops processing the current set of ngx_http_rewrite_module directives as with the break directive;
它不应search与更改的URI匹配的新位置。
只需使用alias 。
location /doc/ { alias /data/doc/site/; index index.html; }
您的代码与rewrite不起作用,因为index做内部redirect。 所以请求stream在你的情况是: /doc/ →(重写) / →(索引,内部redirect) /index.html (proxy_pass)