day 48 Nginx認證及常見應用

12.6 Nginx安裝

  • cd /usr/local/src
  • wget http://nginx.org/download/nginx-1.12.1.tar.gz
  • tar zxvf nginx-1.12.1.tar.gz
  • ./configure --prefix=/usr/local/nginx
  • make  
  • make install
  • vim /etc/init.d/nginx                      #編輯啓動腳本文件,添加特定內容(參考https://coding.net/u/aminglinux/p/aminglinux-book/git/blob/master/D15Z/etc_init.d_nginx )
  • chmod 755 /etc/init.d/nginx
  • chkconfig --add nginx
  • chkconfig nginx on
  • cd /usr/local/nginx/conf/; mv nginx.conf nginx.conf.bak
  • vim nginx.conf                              #編輯nginx配置文件(參考https://coding.net/u/aminglinux/p/aminglinux-book/git/blob/master/D15Z/nginx.conf)
  • /usr/local/nginx/sbin/nginx -t        #語法檢查
  • /etc/init.d/nginx  start                   #啓動nginx
  • netstat -lntp |grep 80 
12.7 Nginx默認虛擬主機

  • vim /usr/local/nginx/conf/nginx.conf                  #編輯nginx配置文件,增加如下內容
include vhost/*.conf
  • mkdir /usr/local/nginx/conf/vhost
  • cd !$;  vim default.conf #加入如下內容
server
{
    listen 80 default_server;  #有這個標記的就是默認虛擬主機
    server_name aaa.com;
    index index.html index.htm index.php;
    root /data/wwwroot/default;
}
  • mkdir -p /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                 #重新加載
  • curl localhost
  • curl -x127.0.0.1:80 123.com
12.8 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;
}
}
  • yum install -y httpd
  • htpasswd -c /usr/local/nginx/conf/htpasswd aming
  • -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 -uaming:passwd                       #訪問狀態碼變爲200
  • 編輯windows的hosts文件,然後在瀏覽器中訪問test.com會有輸入用戶、密碼的彈窗
  • 針對目錄的用戶認證,編輯虛擬主機配置文件,指定特定目錄添加對應內容:
location  /admin/
    {
        auth_basic              "Auth";
        auth_basic_user_file   /usr/local/nginx/conf/htpasswd;
}
12.9 Nginx域名重定向

  • vim /usr/local/nginx/conf/vhost/test.com.conf                              #編輯虛擬主機配置文件,更改test.com.conf
server
{
    listen 80;
    server_name test.com test1.com test2.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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章