Working with alias inside location

2020-02-07 06:32发布

问题:

So here's my server block

server {
    listen      80;
    server_name domain.tld;
    root        /var/www/domain.tld/html;
    index       index.php index.html index.htm;

    location / {
    }

    location /phpmyadmin {
        alias /var/www/phpmyadmin;
    }

    location /nginx_status {
        stub_status on;
        access_log  off;
    }

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

browsing http://domain.tld/index.php works fine the only problem im encountering is browsing http://domain.tld/phpmyadmin/. It returns 404 yet the folder /var/www/phpmyadmin exist on the server. Viewing /var/log/nginx/error.log, no error is being logged there yet the access to it is logged in /var/log/nginx/access.log. What could be the problem here?

回答1:

The problem is that phpmyadmin is a PHP application and your location ~ \.php$ block does not point to the correct document root.

You need to construct two PHP locations with different document roots.

If phpmyadmin is located at /var/www/phpmyadmin, you do not need an alias directive, as a root directive will be more efficient. See this document.

server {
    listen      80;
    server_name domain.tld;
    root        /var/www/domain.tld/html;
    index       index.php index.html index.htm;

    location / { 
    }

    location /nginx_status {
        stub_status on;
        access_log  off;
    }

    location ~ \.php$ {
        try_files $uri =404;
        include fastcgi_params;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }

    location ^~ /phpmyadmin {
        root /var/www;

        location ~ \.php$ {
            try_files $uri =404;
            include fastcgi_params;
            fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        }
    }
}

The location ^~ /phpmyadmin is a prefix location that takes precedence over the regex location normally used to process .php files. It contains a location ~ \.php$ block which inherits a value of /var/www for the document root.

It is advisable to include fastcgi_params before defining other fastcgi_param parameters otherwise your custom values may be silently overwritten.

See this document for more.



标签: nginx