Nginx默認虛擬主機
定義默認虛擬主機配置文件,在http下面加入include vhost/*.conf
在/usr/local/nginx/conf/下創建目錄
#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;
}
#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的安裝而生成。
#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做一個對比
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.com
#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.html