nginx 重写索引配置错误

nginx 重写索引配置错误

下面是我们的虚拟服务器设置,我们希望在访问 的时候/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;

它不应该搜索与改变的 URI 匹配的新位置。

答案1

只需使用alias

location /doc/ {
    alias /data/doc/site/;
    index index.html;
}

您的代码rewrite无法正常工作,因为index进行了内部重定向。因此,您的请求流程为:/doc/→ (重写) /→ (索引,内部重定向) /index.html→ (proxy_pass)

相关内容