2

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

2 Answers 2

1

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 ...; } 
7
  • Thanks! This works, however when a php file is requested by its extension (for example domain.com/index.php), instead of executing, it downloads. Here is my config (just the meaningful parts) pastebin.com/ikPx6jtH @RichardSmith Commented Jan 31, 2016 at 13:33
  • Solved it by doing this: pastebin.com/DvJ2xDSs Commented Jan 31, 2016 at 13:57
  • Now the index page returns 404, but everything else works fine. @RichardSmith Commented Jan 31, 2016 at 14:51
  • @BusinessGuy I have updated the answer Commented Jan 31, 2016 at 14:57
  • So what would be my final config then? I tried removing the @php from the try files and then adding the location php (version 2) to the bottom, but that did"nt wotk (404). Commented Jan 31, 2016 at 15:13
0

Thanks to @RichardSmith, it has been solved!

Here is my final config: http://pastebin.com/TdAz9ad9

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.