Search code examples
phpnginxfpmtrailing-slash

nginx configuration with no trailing slash


I am trying to configure my nginx. I want it to serve a php file: dir/index.php,but do it the way that i can acces it with localhost/dir request (with no trailing slash) without invoking nginx 301 redirect. I tried all of the solutions found here, however failed. Can you please explain how can i reach this goal? This is my config:

server {
access_log /var/log/nginx/access_log combined;
listen 80 default_server;
listen [::]:80 default_server;

root /var/www/mock-api-server.git;
index index.php;

location ~* \.php$ {
    fastcgi_pass unix:/run/php/php7.2-fpm.sock;
    include         fastcgi_params;
    fastcgi_param   SCRIPT_FILENAME    $document_root$fastcgi_script_name;
    fastcgi_param   SCRIPT_NAME        $fastcgi_script_name;
  }
}

Solution

  • You can use try_files to append /index.php to the end of the URI. This must be the last parameter to the try_files statement as the new URI is processed in a different location. See this document for details.

    For example:

    location / {
        try_files $uri $uri/index.php?$args;
    }
    location ~* \.php$ {
        try_files $uri =404;
        ...
    }
    

    The second try_files statement is to avoid passing uncontrolled requests to PHP. If the new URI does not correspond to a real PHP file, a 404 response is returned.