Nginx中配置使用者服務器訪問認證的方法樣本_nginx

來源:互聯網
上載者:User

Nginx超級強大它可以單獨為一個網域名稱設定使用者認證,方法也很簡單我們只要產生使用者認證的使用者名稱和密碼,然後再Nginx添加auth認證配置即可。

Nginx可以為某一個網域名稱單獨加使用者認證,具體做法如下:

1. 產生使用者認證的使用者名稱和密碼:

#wget -c soft.vpser.net/lnmp/ext/htpasswd.sh;bash htpasswd.sh 

根據提示輸入:

使用者名稱:密碼:檔案名稱:

指令碼會自動產生認證檔案,auth.conf內容如下:

/usr/local/nginx/conf/auth.conf 

2. 為Nginx添加auth認證配置

下面以某網域名稱下面的auth目錄為例,在網域名稱的server段裡加上如下代碼:

location ^~ /auth/ { location ~ .*.(php|php5)?$ { fastcgi_pass unix:/tmp/php-cgi.sock; fastcgi_index index.php; include fcgi.conf; } auth_basic "Authorized users only"; auth_basic_user_file /usr/local/nginx/conf/auth.conf } 

auth_basic_user_file 為htpasswd檔案的路徑

3. 重啟Nginx

訪問http://yourdomainname/auth/ 就會提示輸入使用者名稱和密碼。

如果我們只想為目錄增加使用者認證上面方法顯示不行,下面我來介紹具體目錄使用者認證。

為目錄增加使用者認證( auth basic)。

nginx的auth_basic認證採用與apache相容的密碼檔案,因此我們需要通過apache的htpasswd產生密碼檔案。

首先尋找你系統上的htpasswd:

find / –name htpasswd 

一般CentOS都會裝apache的,位置在:

/usr/bin/htpasswd 

如果沒找到那就自行安裝:

yum install apache 

並找到htpasswd檔案地址。

找到htpasswd檔案後,我們來建立一個使用者,比如這個使用者叫:xiaoquan

/usr/bin/htpasswd –c /usr/local/ngnix/conf/authdb xiaoquan 

上面的命令在nginx的設定檔目錄建立了使用者為xiaoquan的authdb密碼檔案,當然你也可以建立的在其他地方,此處nginx設定檔使用比較方便。

上面的命令輸入斷行符號後會得到提示輸入密碼的提示資訊,輸入兩次,即可添加成功。

接著修改nginx的設定檔,在某個需要加auth_basic的server配置下添加如下內容:

location /admin/ { auth_basic "QuanLei Auth."; auth_basic_user_file /usr/local/ngnix/conf/authdb; } 
最後讓nginx使用最新的配置:
/usr/local/ngnix/sbin/nginx -s reload 

補充一下,如果你使用了叢集環境,那麼還需要加Proxy_Pass:

location /admin/ { proxy_pass http://cluster/mgmt/; auth_basic "QuanLei Auth."; auth_basic_user_file /usr/local/ngnix/conf/authdb; } 

PS:使用perl指令碼來實現的方法(代碼如下:)

#! /usr/bin/perl -w  #filename: add_ftp_user.pl  use strict;  #  print "#example: user:passwd\n";  while (<STDIN>) {    exit if ($_ =~/^\n/);    chomp;    (my $user, my $pass) = split /:/, $_, 2;    my $crypt = crypt $pass, '$1$' . gensalt(8);    print "$user:$crypt\n";  }  sub gensalt {    my $count = shift;    my @salt = ('.', '/', 0 .. 9, 'A' .. 'Z', 'a' .. 'z');    my $s;    $s .= $salt[rand @salt] for (1 .. $count);    return $s;  } 

為指令碼賦予可執行許可權:

chmod o+x add_user.pl

指令碼使用方法:

./add_user.pluser:password

把產生的使用者名稱密碼粘貼到/usr/local/nginx/conf/vhost/nginx_passwd檔案中即可

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.