1. 程式人生 > 實用技巧 >curl命令訪問nginx出現301是什麼原因?

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後面記得加上/
再來使用瀏覽器訪問,是可以正常訪問該網站的。效果與上面的圖片一樣。