Nginx Password Protect 403 Forbidden

2019-08-02 03:14发布

问题:

I am running CentOS 6 with nginx. It is currently running perfectly, I am trying to password protect my admin directory.I can successfully login. However, I get a 403 Forbbiden when I try to view the main index page (index.php) in the directory.

2013/04/18 02:10:17 [error] 17166#0: *24 directory index of "/usr/share/ngin/html /somedir/" is forbidden, client: XXX, server: mysite.com, request: "GET /somedir/ HTTP/1.1",  host: "mysite.com"

I have double checked permissions on the ".htpasswd" file. It belongs to "root:root" with chmod 640. I have also tried setting owner ship to "nginx:nginx" and the error still persists.

This is how I am getting htpasswd working:

location ~ ^/([^/]*)/(.*) {
    if (-f $document_root/$1/.htpasswd) {
            error_page 599 = @auth;
            return 599;
    }
}

location @auth {
    auth_basic "Password-protected";
    auth_basic_user_file $document_root/$1/.htpasswd;
}

回答1:

Though the question is pretty old, but I must put my solution here to help others. This very problem was like my pain in somewhere.

I probably have read out (and implemented/tried) almost all possible threads available online (till date) but none solved this "403 Forbidden" nginx issue all-together:

I will write down the steps from beginning: ( block my site access ):

1> We will create a hidden file called .htpasswd in the /etc/nginx

sudo sh -c "echo -n 'usernamee:' >> /etc/nginx/.htpasswd"

2> Now add an encrypted password to the given username

sudo sh -c "openssl passwd -apr1 >> /etc/nginx/.htpasswd"

This will ask you to enter a password and confirm it.

3> Now we need to setup nginx to check our newly created .htpasswd before serving any content.

location / {
        try_files $uri $uri/ /index.php?$query_string; # as per my configuration

        auth_basic "Authorized access only";
        auth_basic_user_file .htpasswd;
}

4> Finally restart the server to take effect

sudo service nginx restart

Now browse the url:

Please note: I didnt do any alteration in permissions. By default the file permission for htpasswd will be set at the time of creation, which will look something like this:

-rw-r--r-- 1 root root 42 Feb 12 12:22 .htpasswd



回答2:

Read the error carefully. You are missing an index.html or similar.



标签: nginx