  
<div id="snippet_109" class="snippet">
  <h2><a href="/snippets/109-Password-protecting-a-folder-resource-with-Nginx" title="Password protecting a folder/resource with Nginx - Shell Script (Bash) - perl, ruby, nginx, auth_basic, htpasswd">Password protecting a folder/resource with Nginx</a></h2>
  <div class="details">
    <a style="background-color: #FFFF94;" href="http://snippets.aktagon.com/languages/131-Shell-Script-Bash-">
      Shell Script (Bash)</a> posted over 2 years ago by christian
          
  </div>

  <div class="body">
    <p>First add the following to your Nginx configuration file:</p>


	<p><pre class="active4d"><span class="line-numbers">   1 </span> location / {
<span class="line-numbers">   2 </span>   auth_basic            <span class="String"><span class="String">&quot;</span>Restricted<span class="String">&quot;</span></span><span class="Operator">;</span>
<span class="line-numbers">   3 </span>   auth_basic_user_file  /etc/nginx/htpasswd<span class="Operator">;</span>
<span class="line-numbers">   4 </span> }
</pre></p>


	<p>Then create the htpasswd file:
<pre class="active4d"><span class="line-numbers">   1 </span> <span class="LineComment"><span class="LineComment">#</span> this be passwords</span>
<span class="line-numbers">   2 </span> thisbetheusername:thisbeencryptedpass:yercomment
</pre></p>


	<p>To generate a htpasswd password without installing Apache you can use the following Perl or Ruby code:</p>


	<p><strong>Perl</strong>
<pre class="active4d"><span class="line-numbers">   1 </span> perl -le <span class="String"><span class="String">'</span>print crypt(&quot;password&quot;, &quot;salt&quot;)<span class="String">'</span></span>
</pre></p>


	<p><strong>Ruby (run in irb)</strong>
<pre class="active4d"><span class="line-numbers">   1 </span> <span class="String"><span class="String">&quot;</span>password<span class="String">&quot;</span></span>.crypt(<span class="String"><span class="String">&quot;</span>salt<span class="String">&quot;</span></span>)
</pre></p>


	<p>The crypt() method uses 56-bit  DES  encryption, which is used in /etc/passwd and htpasswd.</p>
  </div>

  <div style="font-size: 0.8em;margin:0.5em;">
    
      Tagged <a href="/tags/20-perl">perl</a>, <a href="/tags/8-ruby">ruby</a>, <a href="/tags/143-nginx">nginx</a>, <a href="/tags/276-auth-basic">auth_basic</a>, <a href="/tags/277-htpasswd">htpasswd</a>
    
    
  </div>
</div>






