shark255
shark255

Reputation: 45

Why additional location in nginx conf returns 404 code?

I have this configuration for my virtual host:

server {
    listen 80;
    root /var/www/home;
    access_log /var/www/home/access.log;
    error_log /var/www/home/error.log;

    index index.php index.html index.htm;

    server_name home;

    location / {
        try_files $uri $uri/ /index.php?$args; #if doesn't exist, send it to index.php
    }

    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/run/php/php-fpm.sock;

        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        fastcgi_param PHP_VALUE "error_log=/var/www/home/php_errors.log";
    }

    location ~* /Admin {
        allow 127.0.0.1;
        deny all;
    }
}

When I am trying to access page /Admin nginx returns 404 code with successful html content generated by php. When location with /Admin removed, everything goes well.

How to get what is the problem with additional location ?

Upvotes: 1

Views: 1300

Answers (1)

Richard Smith
Richard Smith

Reputation: 49702

You should read this document to understand the precedence order of the various kinds of location block.

So, you could place your regex location above the location ~ \.php$ block to allow it to take precedence, or change it to:

location ^~ /Admin { ... }

which is a prefix location that takes precedence over any regex location (in which case its order within the file becomes irrelevant).

The second problem is the purpose of the allow 127.0.0.1 statement. Are you are expecting to execute .php files with an /Admin prefix from a client at 127.0.0.1?

Your admin location block contains no code to execute .php files. If the intention is to execute .php files with an /Admin prefix, you could try:

location ~ \.php$ {
    try_files $uri =404;
    fastcgi_pass unix:/run/php/php-fpm.sock;

    include fastcgi_params;
    fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
    fastcgi_param PHP_VALUE "error_log=/var/www/home/php_errors.log";
}

location ^~ /Admin {
    allow 127.0.0.1;
    deny all;

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass unix:/run/php/php-fpm.sock;

        include fastcgi_params;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
    }
}

You may want to use the include directive to move common statements into a separate file.

See how nginx processes a request.

Upvotes: 1

Related Questions