Nginx默認虛擬主機
定義默認虛擬主機配置文件,在http下面加入include vhost/*.confphp
在/usr/local/nginx/conf/下建立目錄html
#mkdir vhost/ //建立vhost目錄 #cd vhost/ //進入目錄
#vim aaa.com.conf //編輯文件
server
{
listen 80 default_server; // 有這個標記的就是默認虛擬主機
server_name aaa.com;
index index.html index.htm index.php;
root /data/wwwroot/default;
}nginx
#mkdir /data/wwwroot/default //建立目錄
#echo 「This is a default site.」>/data/wwwroot/default/index.html
#/usr/local/nginx/sbin/nginx -t //檢測語句是否正確
#/usr/local/nginx/sbin/nginx -s reload //從新加載nginx
#curl -x127.0.0.1:80 aaa.com //測試
Nginx用戶認證
#vim /usr/local/nginx/conf/vhost/test.com.conf //寫入以下內容
server { listen 80; server_name test.com; index index.html index.htm index.php; root /data/wwwroot/test.com; location / { auth_basic "Auth"; auth_basic_user_file /usr/local/nginx/conf/htpasswd; //密碼所在的位置文件 } }
htpasswd是apache的一個工具,該工具主要用於創建和更新存儲用戶名、密碼的文本文件,主要用於對基於http用戶的認證。htpasswd的安裝很簡單,它是隨apache的安裝而生成。apache
#yum install -y httpd //下載httpd包
#htpasswd -c /usr/local/nginx/conf/htpasswd zenwen //生成密碼文件
#/usr/local/nginx/sbin/nginx -t && -s reload //測試配置並從新加載
#mkdir /data/wwwroot/test.com //建立目錄
#echo 「test.com」>/data/wwwroot/test.com/index.html
#curl -x127.0.0.1:80 test.com -I //狀態碼爲401說明須要驗證
#curl -uzenwen:passwd -x127.0.0.1:80 test.com -I // 訪問狀態碼變爲200
針對目錄的用戶認證 當訪問admin時,只須要在location /加上admin目錄就能夠對admin進行用戶的驗證 location /admin/ { auth_basic "Auth"; auth_basic_user_file /usr/local/nginx/conf/htpasswd; }
nginx域名重定向
更改test.com.conf server{ listen 80; server_name test.comtest1.comtest2.com; index index.html index.htm index.php; root /data/wwwroot/test.com; if ($host != 'test.com' ) { rewrite ^/(.*)$ http://test.com/$1 permanent; } }
server_name後面支持寫多個域名,這裏要和httpd作一個對比 vim
permanent爲永久重定向,狀態碼爲301,若是寫redirect則爲302
# /usr/local/nginx/sbin/nginx -t //檢測語法
#/usr/local/nginx/sbin/nginx -s reload //從新加載
#curl -x127.0.0.1:80 test2.com/index.html -I //測試
HTTP/1.1 301 Moved Permanently
Server: nginx/1.12.1
Date: Wed, 03 Jan 2018 02:45:07 GMT
Content-Type: text/html
Content-Length: 185
Connection: keep-alive
Location: http://test.com/index.html //直接重定向到了test.comcurl
#curl -x127.0.0.1:80 test1.com/index.html -I //顯示狀態碼爲301
HTTP/1.1 301 Moved Permanently
Server: nginx/1.12.1
Date: Wed, 03 Jan 2018 06:53:13 GMT
Content-Type: text/html
Content-Length: 185
Connection: keep-alive
Location: http://test.com/index.htmlide