2

How can I password protect a single ph php script in Nginx. I'm using nginx as the webserver and proxying over to php-fastcgi. I can't get the location blocks to behave as expected.

Here's a snippet of what I'm trying.

location /admin\.php$ {
    auth_basic "Valid User Required";
    auth_basic_user_file /etc/nginx/http-auth;
}
location ~\.php$ {
    root /var/www/nginx/vhosts/site;
    include /etc/nginx/fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_pass phpfcgi;
}

2 Answers 2

1

First issue:

You are matching against a prefix string instead of a regular expression:

  1. The prefix string is matched literally.
  2. Even if a prefix string is matched, the search continues with the regular expression below (~\.php$). If that matches, the prefix string match is ignored.

Solution to issue #1:

Add a ~ to perform a regular expression match: ~/admin\.php$.

Second issue:

Now that your block matches, you want to pass php scripts inside it to fastcgi, otherwise they'll be served as text files, without being parsed.

Solution to issue #2:

Nest a ~\.php$ location block inside the ~/admin\.php$ location block, for the final result shown below:

location ~/admin\.php$ {
    auth_basic "Valid User Required";
    auth_basic_user_file /etc/nginx/http-auth;
    location ~\.php$ {
        root /var/www/nginx/vhosts/site;
        include /etc/nginx/fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_pass phpfcgi;
    }
}
location ~\.php$ {
    root /var/www/nginx/vhosts/site;
    include /etc/nginx/fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_pass phpfcgi;
}

Reference:

See this pertaining post, this answer on location blocks precedence, and the Nginx docs on the topic.

Sign up to request clarification or add additional context in comments.

Comments

0
location /admin\.php$ {
    auth_basic "Valid User Required";
    auth_basic_user_file /etc/nginx/http-auth;
+    root /var/www/nginx/vhosts/site;
+    include /etc/nginx/fastcgi_params;
+    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
+    fastcgi_pass phpfcgi;
}

May be this helps to you.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.