Nginx Password Protect Entire Port Number 8081

directorynginxpasswordpassword-protectedUbuntu

I'm trying to password protect an entire port on my website–https://domain.com:8081 and http://domain.com:8081

I have tried editing /etc/nginx/sites-enabled/domain.com.vhost by adding the following within the server block to no avail (which I got from this link, except that link is in regards to password protecting directories rather than ports):

location ^~ :8081 {
auth_basic            "Restricted Area";
auth_basic_user_file  conf/htpasswd;
}

I also tried "location :8081", but this also did not work.

How can I password protect port 8081 (or any other port I desire for that matter)?

If it makes any difference, I'm using Ubuntu 14.04.1 LTS with Nginx 1.4.6.

Thanks.

[EDIT]

When implementing Nathan's solution, when going to https://domain.com:8081/phpmyadmin/ (SSL), it brings up the prompt for a username and password, but gives me a "500 Internal Server Error" page. Here's what shows on the Nginx error log:

[crit] 3390#0: *154 open() "/etc/nginx/conf/htpasswd" failed (13: Permission denied), client: 152.35.52.108, server: domain.com, request: "GET /phpmyadmin/ HTTP/1.1", host: "domain.com:8081"

When going to http://domain.com:8081/phpmyadmin/ (non-SSL), it gives me "400 Bad Request The plain HTTP request was sent to HTTPS port". Nothing registers for this on the error log; instead, the following appears on the Nginx access log:

"GET /phpmyadmin/ HTTP/1.1" 40.1" 400 279 "-" "[user agent]"

Best Answer

I'm assuming you have a separate server { block for this port...so you'd just protect the / directory from within that server block:

location / {
auth_basic            "Restricted Area";
auth_basic_user_file  conf/htpasswd;
}

So:

server {
listen 8081;
server_name whateveryouwant;
root /path/to/root/folder;
location / {
    auth_basic            "Restricted Area";
    auth_basic_user_file  conf/htpasswd;
    }
}

I haven't tested this, but that's how it should look.