nginx重定向循环,index.html

时间:2014-02-11 14:53:27

标签: nginx

这看起来很荒谬但我在一个多小时的搜索中找不到合适的答案。 当我访问“http://oa.wechat.com/screen/index.html”时,它将导致301重定向循环,如下所示:

"GET /screen/ HTTP/1.1" 301
"GET /screen/index.html/ HTTP/1.1" 301 
"GET /screen/index.html/index.html/ HTTP/1.1" 301 
... 

nginx verson:1.5.6 nginx.conf

    server {
        listen  80;
        server_name oa.wechat.com;

        location ~ ^/screen/ {
            alias /data/screen/static/;
            index index.html;
        }  
    } 

谁能告诉我原因?非常感谢。

我检查过nginx文件。正确使用'别名':

    # use normal match like this
    location  /i/ {
      alias  /spool/w3/images/;
    }

    # use regex match like this
    location ~ ^/download/(.*)$ {
      alias /home/website/files/$1;
    }

使用'别名'的错误方法是:

    location ~ ^/screen/ {
        alias /data/screen/static/;
        index index.html;
    }  

在这种情况下,请求将被视为目录请求,而不是文件请求,这将导致重定向循环。

无论如何,非常感谢Flesh!

2 个答案:

答案 0 :(得分:4)

它已经尝试访问该目录中的index.html,因为它是nginx的index directive的默认值。问题是你在location block中使用index指令,它具有特殊含义并执行内部重定向(如文档所述)。

除非您知道自己在做什么,否则请在server block内设置index指令。我们最终得到以下server块(请务必阅读评论)。

server {
    # Both default values and not needed at all!
    #index      index.html;
    #listen     80;
    server_name oa.wechat.com;

    # Do not use regular expressions to match the beginning of a
    # requested URI without protecting it by a regular location!
    location ^~ /screen/ {
        alias /data/screen/static/;
    }

}

location示例

server {

    # Won't work because the /data is considered the new document root and
    # the new location matches the regular expression again.
    location ~ ^/screen/ {
        alias /data/screen/static/;
    }

    # Should work because the outer location limits the inner location
    # to start with the real document root (untested)
    location / {
        location ~ ^/screen/ {
            alias /data/screen/static/;
        }
    }

    # Should work as well above reason (untested)
    location / {
        location ~ ^(/screen/) {
            alias /data$1static/;
        }
    }

    # Might work as well because we are using the matching group
    # VERY BAD because we have a regular expression outside any regular location!
    location ~ ^(/screen/) {
        alias /data$1static/;
    }

    # Always works and allows nesting of more directives and is totally save
    location ^~ /screen/ {
        alias /data/screen/static/;
    }

}

网站链接

答案 1 :(得分:1)

您应该从^移动^/screen/位置修饰符,然后在^之前添加~,如下所示:

 `location ^~ /screen/ {
     alias /data/screen/static/;
     index index.html;
  }`