Search code examples
mod-rewritenginxpassword-protection.htpasswd

nginx htpasswd protect works fine for the whole site, but not a subdirectory with rewrite


I have ecountered a strange problem, here is my NGINX conf file

# For whole site
location / {
    auth_basic "Restricted";
    auth_basic_user_file /home/john/.htpasswd;
}

# Forum rewrite
location /forum/ {
    try_files $uri $uri/ @forum;
}
location @forum {
    rewrite ^/forum/(.+)$ /forum/index.php?p=$1 last;
}

The protection works fine for the whole site, but it doesn't work for this particular forum folder that was defined with "location" command if URLs are:

https://mysite.com/forum/
https://mysite.com/forum/discussion/9/help-support

and was able to access it directly without entering any password. But strangely it works without the trailing slash / like:

https://mysite.com/forum

prompting the username and password. Repeating the auth_basic protection command to the forum location like:

location /forum/ {
    auth_basic "Restricted";
    auth_basic_user_file /home/john/.htpasswd;
    try_files $uri $uri/ @forum;
}

didn't help either. Any clues? Thank you!


Solution

  • since you want auth_basic active for the whole site, you can just include inside the server block or the http(s) block

    auth_basic "Restricted";
    auth_basic_user_file /home/john/.htpasswd;
    
    # Forum rewrite
    location /forum/ {
      try_files $uri $uri/ @forum;
    }
    location @forum {
      rewrite ^/forum/(.+)$ /forum/index.php?p=$1 last;
    }