今天遇到一个Nginx location 301问题,比如我配置如下:

#前端通过反向代理,把80端口映射到后端8000端口
server{
    listen 8000;
    server_name domain;
    
    location /test {
        rewrite ^/test/(.*)$ /test/index.php/$1;
    }
    
    ……
}

当访问http://domain/test/的时候一切正常,但是在访问http://domain/test的时候却返回301跳转,指向的地址http://domain:8000/test/。


这里有两个问题,第一,为什么跳转;第二,为什么给我加8000,第一个问题,看官网文档就可以知道

If a location is defined by a prefix string that ends with the slash character, and requests are processed by one of proxy_passfastcgi_passuwsgi_passscgi_pass, or memcached_pass, then the special processing is performed. In response to a request with URI equal to this string, but without the trailing slash, a permanent redirect with the code 301 will be returned to the requested URI with the slash appended. If this is not desired, an exact match of the URI and location could be defined like this:

location /user/ {
    proxy_pass http://user.example.com;
}

location = /user {
    proxy_pass http://login.example.com;
}

原因就是Nginx判断所访问的是一个目录,就会进行301跳转加上斜线,但他的方案针对*_pass等,但对于第二个问题还是没解决,我们默认的端口就是80端口,那返回的时候不加端口号不久行了吗?是的,没错

port_in_redirect on | off;

Enables or disables specifying the port in redirects issued by nginx.

The use of the primary server name in redirects is controlled by the server_name_in_redirectdirective.

默认是开启的,也就是默认会带port返回,如果置为off就不会返回来,这样问题就因人而结了,反问没有斜线的地址会自动加上斜线通过301跳转。


       对于地址不是80端口的大家可以自行测试,欢迎反馈!