一個重要的Web服務器任務是提供文件(如圖像或靜態HTML頁面)。
根據請求,文件將從不同的本地目錄提供:/data/www(可能包含HTML文件)和/ data/images(包含圖像)。這將需要編輯配置文件,并使用兩個位置塊在http塊內設置服務器塊。 ? ? ?( 推薦學習:nginx使用?)
首先,創建/data/www目錄,并將一個包含任何文本內容的index.html文件放入其中,并創建/data/images目錄并在其中放置一些圖像。創建兩個目錄 –
[root@localhost?~]#?mkdir?-p?/data/www [root@localhost?~]#?mkdir?-p?/data/images [root@localhost?~]#
分別在上面創建的兩個目錄中放入兩個文件:/data/www/index.html 和 /data/images/logo.png,/data/www/index.html文件的內容就一行,如下 –
<h2>?New?Static?WebSite?Demo.</h2>
接下來,打開配置文件(/usr/local/nginx/conf/nginx.conf)。 默認的配置文件已經包含了服務器塊的幾個示例,大部分是注釋掉的。 現在注釋掉所有這樣的塊,并啟動一個新的服務器塊:
http?{ ????server?{ ????} }
通常,配置文件可以包括服務器監聽的端口和服務器名稱區分的幾個server塊。當nginx決定哪個服務器處理請求后,它會根據服務器塊內部定義的location指令的參數測試請求頭中指定的URI。
將以下location塊添加到服務器(server)塊:
http?{ ????server?{ ????????location?/?{ ????????????root?/data/www; ????????} ????} }
該location塊指定與請求中的URI相比較的“/”前綴。 對于匹配請求,URI將被添加到root指令中指定的路徑(即/data/www),以形成本地文件系統上所請求文件的路徑。 如果有幾個匹配的location塊,nginx將選擇具有最長前綴來匹配location塊。 上面的location塊提供最短的前綴長度為1,因此只有當所有其他location塊不能提供匹配時,才會使用該塊。
接下來,添加第二個location塊:
http?{ ????server?{ ????????location?/?{ ????????????root?/data/www; ????????} ????????location?/images/?{ ????????????root?/data; ????????} ????} }
它將是以/images/(位置/也匹配這樣的請求,但具有較短前綴,也就是“/images/”比“/”長)的請求來匹配。
server塊的最終配置應如下所示:
server?{ ????location?/?{ ????????root?/data/www; ????} ????location?/images/?{ ????????root?/data; ????} }
這已經是一個在標準端口80上偵聽并且可以在本地機器上訪問的服務器( http://localhost/ )的工作配置。 響應以/images/開頭的URI的請求,服務器將從/data/images目錄發送文件。 例如,響應http://localhost/images/logo.png請求,nginx將發送服務上的/data/images/logo.png文件。 如果文件不存在,nginx將發送一個指示404錯誤的響應。 不以/images/開頭的URI的請求將映射到/data/www目錄。 例如,響應http://localhost/about/example.html請求時,nginx將發送/data/www/about/example.html文件。
要應用新配置,如果尚未啟動nginx或者通過執行以下命令將重載信號發送到nginx的主進程:
[root@localhost?~]#?/usr/local/nginx/sbin/nginx?-t nginx:?the?configuration?file?/usr/local/nginx/conf/nginx.conf?syntax?is?ok nginx:?configuration?file?/usr/local/nginx/conf/nginx.conf?test?is?successful [root@localhost?~]#?/usr/local/nginx/sbin/nginx?-s?reload
如果錯誤或異常導致無法正常工作,可以嘗試查看目錄/usr/local/nginx/logs或/var/log/nginx中的access.log和error.log文件中查找原因。
打開瀏覽器或使用CURL訪問Nginx服務器如下所示 –
完整的nginx.conf文件配置內容如下:
#user??nobody; worker_processes??1; #error_log??logs/error.log; #error_log??logs/error.log??notice; #error_log??logs/error.log??info; #pid????????logs/nginx.pid; events?{ ????worker_connections??1024; } http?{ ????include???????mime.types; ????default_type??application/octet-stream; ????#log_format??main??'$remote_addr?-?$remote_user?[$time_local]?"$request"?' ????#?'$status?$body_bytes_sent?"$http_referer"?' ????#?'"$http_user_agent"?"$http_x_forwarded_for"'; ????#access_log??logs/access.log??main; ????sendfile????????on; ????#tcp_nopush?????on; ????#keepalive_timeout??0; ????keepalive_timeout??65; ????#gzip??on; ????##?新服務(靜態網站) ????server?{ ????????location?/?{ ????????????root?/data/www; ????????} ????????location?/images/?{ ????????????root?/data; ????????} ????} }