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!

Answers


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;
}

Need Your Help

How to show image instead of text in WebGrid header

asp.net-mvc-4 razor webgrid

I am trying to use the WebGrid in My MVC 4 application and in my grid I want to display images in header .So please give some example for this, how can I achieve this. I tried searching on internet...

InnoDB row level locking performance - how many rows?

mysql performance innodb

I just read a lot of stuff about MyISAM and InnoDB as I have to decide which type to use.