Nginx net urls how to rewrite a folder as an argument using try_files

I am writing a simple CMS in PHP. Pages (markup files) and images refer to this (respectively):

example.org/?q=about.md example.org/?i=photo.jpg 

Optionally, I would like to use pure URLs with Nginx to make the same requests look like:

 example.org/about example.org/photo.jpg 

I rather use try_files than if and rewrite , but after several hours of work, I cannot get it to work.

 location / { try_files $uri $uri/ /?q=$uri.md =404; } location ~ \.(gif|jpg|png)$ { try_files $uri /?i=$uri =404; } 

I don’t understand why the above code does not work (URLs with argument work fine, but beautiful ones give 404 errors).

Is there something wrong with passing the folder name as an argument using $uri ?
Do I need to avoid some weird characters (other than my homeowner)?


To be thorough, I run Nginx 1.6.2 using the standard nginx.conf. Here is the rest of my server block:

 server_name example.org; root /srv/example/; index index.html index.htm index.php; (...) location ~ \.php$ { fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_index index.php; include fastcgi.conf; } 

and fastcgi.conf are also standard.

+7
php uri url-rewriting nginx
source share
1 answer

I managed to get your example to work by simply omitting =404 :

 location / { try_files $uri $uri/ /?q=$uri.md; } location ~ \.(gif|jpg|png)$ { try_files $uri /?i=$uri; } 

Quoting Guide :

Checks for files in the specified order and uses the first file found to process the request; [...] If none of the files are found , an internal redirect to uri is specified in the last parameter.

You want this internal redirect, which occurs only if none of the files are found, but =404 always found.

+3
source share

All Articles