Nginx remove characters from variable

nginx

Basically what i want to do is put the requested URL into a variable, and then remove a character (like /) and get a new variable.

I'm trying to implement trailing slashes at the end of the URL's; This works, but i want to do it for all files:

location /examplehtmlfile/ {
   try_files = $uri $uri/ examplehtmlfile.html
}

Otherwise if i add a trailing slash at the end it produces a 404 error.

So what i want to do is add to to try_files directive (for the main / location)
something like this:

try_files = $uri $uri/ /$uriwithoutslash.html /$uriwithoutslash.php

Thanks

Best Answer

You need to rewrite the $uri variable if it contains a trailing slash. This is an internal rewrite so it will not affect the URL as it appears to your customers.

location ~ ./$ { rewrite ^(.+)/$ $1 last; }

Your main location can only test for the existence of static content. PHP files need to be handled in a different location block.

location / {
    try_files $uri $uri.html $uri/index.html @php;
}

The existence of PHP files can be tested in the named location:

location @php {
    try_files $uri.php $uri/index.php =404;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_pass ...;
}

The =404 could be replaced with a default URI, for example: /index.php

A root directive is also required, but an index directive is not consulted.

EDIT:

If you need to support URIs with the .php extension too, you can either rewrite them and add the slash or duplicate the PHP location block. Either:

location ~ \.php$ {
    rewrite ^(.*)\.php$ $1/ last;
}

Or:

location ~ \.php$ {
    try_files $uri =404;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_pass ...;
}
Related Topic