curl命令访问nginx出现301是什么原因?

今天有个人问我,它配置好了nginx,是没有问题的,可是访问的时候,就是报301重定向问题。然后我问他使用的什么工具访问web的?是浏览器吗?他说不是,用的curl命令。那么在此我顺便总结一下这个问题:
假如现在我有个前段页面dlib包,这是一个c++库的帮助文档,我放在nginx的访问路径下,我的nginx是编译安装的,在/usr/local/nginx目录下,那么现在我把dlib放在html里面。

[root@master2 html]# pwd
/usr/local/nginx/html
[root@master2 html]# ls -l
total 16
-rw-r--r--  1 nginx nginx  494 Aug 20 11:26 50x.html
drwxr-xr-x 10 nginx nginx 8192 Aug 21 17:39 dlib

然后我配置一下nginx文件

server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location /dlib {
            root   html;
            index  index.html index.htm;
        }
}

现在我访问一下,使用curl命令访问

[root@master2 nginx]# curl http://192.168.50.129/dlib
<html>
<head><title>301 Moved Permanently</title></head>
<body>
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx/1.16.1</center>
</body>
</html>

确实出现了301重定向,那么现在我打开浏览器访问

使用浏览器访问是完全没有问题的。
其实主要的原因就是使用curl命令访问需要在url的末尾加上/,加上/,浏览器访问一次,不加/,浏览器访问两次。而对于不加/使用curl来访问,第一次匹配后是301重定向,此时还会再进行第二次匹配,但是curl没有这么强大,只支持一次,所以报的就是301重定向的问题了。但是浏览器很强大,加了/浏览器会指向一个目录,目录的话会直接读取默认文件以index结尾等等。没有/会先尝试读取文件,如果没有文件再取找与该文件同名的目录,最后才读目录下的默认文件,所以就看到了正常页面。
所以现在可以在url末尾加上/来访问

[root@master2 nginx]# curl http://192.168.50.129/dlib/
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html xmlns:gcse="googleCustomSearch"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><link rel="shortcut icon
# 内容很多,截取一部分展示

下面是自己的一点简单记录
上面配置文件中也可以用alias实现。

server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            alias   html/dlib/;
            index  index.html index.htm;
        }
}

注意上面的alias的uri后面记得加上/
再来使用浏览器访问,是可以正常访问该网站的。效果与上面的图片一样。

原文地址:https://www.cnblogs.com/FengGeBlog/p/13542627.html