Nginx clean urls, how to rewrite a folder as an argument with try

I'm writing a simple CMS in PHP. Pages (markdown files) and images are accessed like this (respectively):

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

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

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

I rather use try_files than if and rewrite but after experimenting for hours, I can't 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 doesn't work (urls with argument work fine but the pretty ones give 404 errors).

Is there something wrong with passing the folder name as an argument using $uri ?
Do I need to escape some weird characters (apart from my landlord)?


To be thorough, I'm running Nginx 1.6.2, using the standard nginx.conf. Here's 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 is also standard.


I was able to get your example to work by simply omitting the =404 :

location / {
    try_files $uri $uri/ /?q=$uri.md;
}

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

Quoting the manual:

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

You want that internal redirect, which is only happening if none of the files are found, but =404 is always found.

链接地址: http://www.djcxy.com/p/25628.html

上一篇: 如何在Android中应用视频过滤?

下一篇: Nginx的清洁URL,如何用try尝试重写一个文件夹作为参数