nginx關於root與alias的區別

結論

配置demo:html

location xxx {
    root yyy
}

瀏覽器訪問 xxx,實際訪問的是 yyy/xxx
瀏覽器訪問 xxx/abc.html,實際訪問的是 yyy/xxx/abc.html
瀏覽器訪問 xxx/ccc/abc.html,實際訪問的是 yyy/xxx/ccc/abc.htmlnginx

結論: root屬性,會把root的值(這裏是yyy)加入到訪問路徑(locaition)以前

配置demo:瀏覽器

locaiton xxx {
    # alias必須以 / 結束,不然無效
    alias yyy/ 
}

瀏覽器訪問 xxx,實際訪問的是 yyy
瀏覽器訪問 xxx/abc.html,實際訪問的是 yyy/abc.html
瀏覽器訪問 xxx/ccc/abc.html,實際訪問的是 yyy/ccc/abc.htmlcode

結論:alias屬性,會把alias的值(這裏是yyy)替代訪問路徑匹配的部分(這裏是xxx)

示例

nginx的目錄結構以下:server

nginx/
    -html/
        -index.html
    -logs/
        - access.log
    -conf/
        -nginx.conf

1) 這種配置,http://localhost:8086/access.log,能看到 nginx/logs/access.log,但就別期望能訪問 html目錄下的文檔了htm

server {
    listen       8086;
    server_name  localhost;
    location / {
        root   logs;
    }
}

2) 這種配置,訪問 http://localhost:8086/log/access.log,能看到 nginx/logs/access.log;
訪問 http://localhost:8086/, 能看到 nginx/html/index.htmlblog

server {
    listen       8086;
    server_name  localhost;
    location / {
        root   html;
        index  index.html index.htm;
    }
    # 配置成 location /log/ 或 location /log 均可以
    location /log/ {
        # 不能寫成logs, 必須已 / 結束
        alias logs/;
        # 如下配置沒用也能夠,只是方便你輸入 localhost:8086/log/ 後能,看到nginx/logs/目錄下的全部文件
        autoindex on;
    }
}

3) 這種配置,訪問 http://localhost:8086/logs/access.log,能看到 nginx/logs/access.log;
訪問 http://localhost:8086/, 能看到 nginx/html/index.html文檔

server {
    listen       8086;
    server_name  localhost;
    # http://localhost:8086/ 訪問的是
    # nginx/html/  (而後會自動顯示 index.html 或 index.htm,若是存在這兩個文件之一)
    # 囉嗦的註釋: nginx/html(html是root的值)/(/是location的值)
    location / {
        root   html;
        index  index.html index.htm;
    }
    # http://localhost:8086/logs/ 訪問的是
    # nginx/./logs/
    # .是root的值,logs是location的值
    # 請與第4種錯誤配置進行比較,深刻理解root屬性
    location /logs/ {
        # 寫成./也能夠
        root .;
    }
}

4) 錯誤的配置get

server {
    listen       8086;
    server_name  localhost;
    location / {
        root   html;
        index  index.html index.htm;
    }
    # 這樣子配置是錯的, 請與第三種配置比較一下
    # 關鍵點:root屬性會把root的值加入到最終路徑以前
    # 即: http://localhost:8086/logs/access.log訪問的是:
    # nginx/logs/logs/access.log
    # 由於: nginx/logs(root的值)/logs(locaition的值)/access.log,
    location /logs/ {
        root /logs/;
    }
}

節選:https://www.cnblogs.com/zhang... 這段話:
root屬性指定的值是要加入到最終路徑的,因此訪問的位置變成了 root的值/locaiton的值。而我不想把訪問的URI加入到路徑中。因此就須要使用alias屬性,其會拋棄URI,直接訪問alias指定的位置it

參考:
https://www.cnblogs.com/zhang...
https://www.cnblogs.com/kevin...

相關文章
相關標籤/搜索