在Nginx用htpasswd對網站進行密碼保護的設定方法

來源:互聯網
上載者:User

最後的效果就類似(不同瀏覽器的介面有所不同):

如果認證失敗,就會報HTTP錯誤:401 Authorization Required。

要實現這樣的功能,就需要更改伺服器的配置,並設定好用於登入的使用者名稱和密碼。

首先我們需要更改網站的Nginx的server配置,Ubuntu伺服器的話這個設定檔通常位於/etc/nginx/sites-enabled/,比如我這裡就使用預設的設定檔/etc/nginx/sites-enabled/default來做一個例子:

複製代碼 代碼如下:server {
server_name www.fancycedar.info
root /www/fancycedar

# ...

location / {
# 添加下面兩行
auth_basic "Restricted";
auth_basic_user_file htpasswd;
# ...
}

# ...
}

接下來需要建立htpasswd檔案,這裡有一些細節需要注意:

htpasswd的路徑
和nginx.conf在同一級目錄即可。Ubuntu伺服器的話一般就在/etc/nginx/下面。

htpasswd的內容
每一行為一個使用者,格式為username:password。但是要注意,這裡的password不是明文,而是將password進行crypt(3)加密後的字串。

你可以使用一段PHP代碼來產生htpasswd中的password:

複製代碼 代碼如下:// 密碼明文
$password = 'some password';
// 對密碼進行加密
$password = crypt($password, base64_encode($password));
// 獲得加密後的密碼
echo $password;

然後將字串寫入htpasswd檔案中:

複製代碼 代碼如下:username1:xucqMk13TfooE
username2:YXTfb3xWKOMBM
...

htpasswd的許可權

需要更改htpasswd檔案的許可權,執行如下命令:

複製代碼 代碼如下:sudo chown root:www-data htpasswd
sudo chmod 640 htpasswd

Are You Ready?

當上面的準備工作都做好之後,我們就可以重新載入或者重啟Nginx伺服器了:

複製代碼 代碼如下:sudo /etc/init.d/nginx reload
# or
sudo /etc/init.d/nginx restart

完工。

P.S. 不要忘記你設定的密碼是啥了……

原文連結:http://www.fancycedar.info/2013/06/apache-nginx-htpasswd/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.