Nginx: password protecting wp-login.php: issues

September 27, 2016 157 views
Nginx WordPress Ubuntu

Following the official WordPress documentation page I'm struggling for hours now facing two main problems:

  1. nginx doesn't get my rule
  2. if it gets the block, browsers download the file because nginx suppresses PHP's parsing.

I'm using Virtualmin with the nginx module. Here's the site's conf file:

server {
    root /home/foo/public_html;
    index  index.html index.htm index.php;
    access_log /var/log/virtualmin/foo.com_access_log;
    error_log /var/log/virtualmin/foo.com_error_log;
    fastcgi_param GATEWAY_INTERFACE CGI/1.1;
    fastcgi_param SERVER_SOFTWARE nginx;
    fastcgi_param QUERY_STRING $query_string;
    fastcgi_param REQUEST_METHOD $request_method;
    fastcgi_param CONTENT_TYPE $content_type;
    fastcgi_param CONTENT_LENGTH $content_length;
    fastcgi_param SCRIPT_FILENAME /home/foo/public_html$fastcgi_script_name;
    fastcgi_param SCRIPT_NAME $fastcgi_script_name;
    fastcgi_param REQUEST_URI $request_uri;
    fastcgi_param DOCUMENT_URI $document_uri;
    fastcgi_param DOCUMENT_ROOT /home/foo/public_html;
    fastcgi_param SERVER_PROTOCOL $server_protocol;
    fastcgi_param REMOTE_ADDR $remote_addr;
    fastcgi_param REMOTE_PORT $remote_port;
    fastcgi_param SERVER_ADDR $server_addr;
    fastcgi_param SERVER_PORT $server_port;
    fastcgi_param SERVER_NAME $server_name;
    fastcgi_param HTTPS $https;
        location / {
         try_files $uri $uri/ /index.php?$args;

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass unix:/var/php-nginx/14749874634504.sock/socket;


I'm new to nginx. Where I should put the rule block and what's the exact rule that should be used? thanks in advance.

1 Answer

Here's the solution:

location ^~ /wp-login.php {
           auth_basic  "Login";
           auth_basic_user_file /home/foo/.htpasswd;
          fastcgi_pass unix:/var/php-nginx/14749874634504.sock/socket;

The PHP param(s) is(are) required to make it work. It's not necessary to protect /wp-admin because WP redirects all non-logged in users to wp-login.php.

Hope this helps.

Have another answer? Share your knowledge.