使用 Nginx 限制页面访问权限

文章目录

    写了一个小 web 应用,需要后台提交数据,但是这个页面只允许我一个人访问。
    单独为这个页面增加用户权限系统,有点杀鸡用牛刀的感觉。还好用 Nginx 可以轻松搞定这件事。

    htpasswd

    htpasswd is used to create and update the flat-files used to store usernames and password for basic authentication of HTTP users. 安装方法

    sudo apt-get install apache2-utils
    

    创建用户和密码

    $ sudo htpasswd -c /etc/nginx/.htpasswd myusername
    New password:
    Re-type new password:
    Adding password for user myusername 
    

    担心密码是明文存储的? cat /etc/nginx/.htpasswd

    可以看到只有用户名是明文的,密码做了加密。

    更新 Nginx 配置

    server {
      listen       80;
      server_name  ip_address;
    
      location /backend {
          root   /var/www/sunzhongwei.com;
          index  index.html index.htm;
    
          auth_basic "Restricted";                                
          auth_basic_user_file /etc/nginx/.htpasswd;  
      }
    }
    

    reload nginx

    sudo /etc/init.d/nginx reload
    

    参考

    关于作者 🌱

    我是来自山东烟台的一名开发者,有感兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊,或者关注我的个人公众号“大象工具”, 查看更多联系方式