Nginx玩的就是“頁面輸出”,把新聞的頁面放到新聞的檔案夾裡,把體育的頁面放到體育的檔案夾裡,把動漫的頁面放到動漫的檔案夾裡,然後搭配好各種正則搜尋,這樣使用者在浏覽器的位址欄裡輸入對應的位址,伺服器就回到相應的檔案夾裡去把網頁呈現出來。
location的定位
伺服器裡的nginx.conf配置如圖:
<a href="http://s4.51cto.com/wyfs02/M00/7F/BF/wKioL1crQguy_1juAAA8NJOsgQU939.png" target="_blank"></a>
這個域名的server_name是localhost。location /裡的/指的是 /usr/local/nginx/html 這個目錄,此時,在/usr/local/nginx/html下建立一個叫welcome.html的檔案,裡面的内容是:“welcome to ChrisChan's server"。
然後#nginx -t,檢查一下配置檔案,都OK之後,就#nginx -s reload。
使用浏覽器打開localhost可以看一下效果。
<a href="http://s4.51cto.com/wyfs02/M02/7F/BF/wKioL1crREHhcIMSAAAsxhhJ04g813.png" target="_blank"></a>
但是後面我還設定了一個二階網頁,/nba,雖然它的root也是/usr/local/nginx/html,但是這個index.html卻不可以設定在/usr/local/nginx/html,而是要設定到/usr/local/nginx/html/nba裡。于是在/usr/local/nginx/html/nba這個檔案夾裡,#echo "steven curry is MVP in 2016!" > index.html,同樣重新檢查nginx的配置檔案文法然後重新開機,在浏覽器看一下效果。
<a href="http://s5.51cto.com/wyfs02/M00/7F/BF/wKioL1crRWTTNVKhAAA0tSEb49s180.png" target="_blank"></a>
這裡需要賬号密碼,在配置檔案裡我們已經看到了,賬号密碼都被記錄在/usr/local/nginx/conf/passwd這個檔案夾裡,這樣防止陌生人來通路這個網頁。這個密碼是可以被cookie記錄的,而且上面的提示不可以是中文。
<a href="http://s3.51cto.com/wyfs02/M00/7F/BF/wKioL1crSPawLcNCAAAyzau-l_0175.png" target="_blank"></a>
【總結】可以看出在浏覽器位址欄裡localhost/是指nginx.conf配置的root一大串位址,而localhost/nba裡的檔案對應是root/nba檔案夾裡的。
nginx如何使用者驗證
nginx使用者驗證有很多方法,http://dreamfire.blog.51cto.com/418026/1141385/這個文章就說明了一個方法,但是有一個方法比這個簡單的多,使用ngx_http_auth_basic_module子產品。
在nginx.conf裡對應的網頁寫上
1
2
3
4
5
6
<code> </code><code>location / </code><code>#這裡可以是任何字尾或者不加字尾</code>
<code> </code><code>{</code>
<code> </code><code>auth_basic </code><code>"ABC"</code><code>; </code><code>#“ABC就是使用者登入的提示</code>
<code> </code><code>auth_basic_user_file </code><code>/usr/local/nginx/conf/passwd</code><code>; </code><code>#這裡是密碼檔案的路徑 </code>
<code> </code><code>autoindex on</code>
<code> </code><code>}</code>
備注:一定要注意auth_basic_user_file路徑,否則會不厭其煩的出現403。
然後把配置檔案儲存退出,下面就是生成passwd這個密碼檔案:
<code># printf "chris:$(openssl passwd -crypt 123456)\n" >>conf/htpasswd</code>
<code># cat conf/htpasswd </code>
<code>chris:xyJkVhXGAZ8tM <----這個就是賬号密碼,注意!真實的密碼是123456</code>
然後#nginx -s reload,檢視一下效果即可。如果使用者認證失敗,就會401 authorization required,這個密碼是會被cookie記錄的。
本文轉自 蘇幕遮618 51CTO部落格,原文連結:http://blog.51cto.com/chenx1242/1770572