How to set access control for the static files that served by nginx

Table of Contents

To set an access password for static files served by Nginx, you can use HTTP Basic Authentication. Follow these steps:


1. Install htpasswd (if not already installed)

The htpasswd utility is part of the Apache apache2-utils package on Debian-based systems or httpd-tools on RHEL-based systems.

Debian/Ubuntu:

sudo apt update
sudo apt install apache2-utils

RHEL/CentOS:

sudo yum install httpd-tools

2. Create a Password File

Use the htpasswd command to create a password file. Replace username with the desired username.

sudo htpasswd -c /etc/nginx/.htpasswd username
  • You’ll be prompted to enter and confirm a password.
  • Use the -c flag only the first time to create the file. Omit it when adding additional users.

Example:

sudo htpasswd /etc/nginx/.htpasswd anotheruser

3. Update Nginx Configuration

Edit your Nginx configuration file to enable basic authentication for the location serving the static files.

Example:

If your static files are served from /var/www/static:

server {
    listen 80;
    server_name example.com;

    location /static/ {
        root /var/www;
        auth_basic "Restricted Access";
        auth_basic_user_file /etc/nginx/.htpasswd;
    }
}
  • auth_basic: Sets the realm name (visible in the authentication dialog box).
  • auth_basic_user_file: Specifies the path to the .htpasswd file.

4. Test Configuration

Check the Nginx configuration for syntax errors:

sudo nginx -t

If the test is successful, reload Nginx:

sudo systemctl reload nginx

5. Verify

  • Open your browser and navigate to the URL serving the static files.
  • You should be prompted for a username and password.

Additional Tips

  • Ensure the .htpasswd file is stored securely and only accessible by Nginx (e.g., permissions set to 600).
  • You can use HTTPS to encrypt the connection and enhance security.

Comments |0|

Legend *) Required fields are marked
**) You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>
Category: 似水流年