php – Nginx清理网址,如何使用try_files将文件夹重写为参数

我正在用PHP编写一个简单的CMS.页面(降价文件)和图像可以像这样(分别)访问:

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

或者,我想使用带有Nginx的干净URL,使相同的请求看起来像这样:

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

我宁愿使用try_files而不是if和rewrite,但经过几个小时的实验,我无法让它工作.

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

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

我不明白为什么上面的代码不起作用(带参数的网址工作正常但漂亮的代码有404错误).

使用$uri将文件夹名称作为参数传递是否有问题?
我是否需要逃避一些奇怪的角色(除了我的房东)?

为了彻底,我使用标准的nginx.conf运行Nginx 1.6.2.
这是我的服务器块的其余部分:

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;
}

和fastcgi.conf也是标准的.

通过简单地省略= 404,我能够让你的例子工作:

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

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

引用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.

您需要内部重定向,只有在找不到任何文件时才会发生,但始终找到= 404.

相关文章

文章浏览阅读3.7k次,点赞2次,收藏5次。Nginx学习笔记一、N...
文章浏览阅读1.7w次,点赞14次,收藏61次。我们在使用容器的...
文章浏览阅读1.4k次。当用户在访问网站的过程中遇到404错误时...
文章浏览阅读2.7k次。docker 和 docker-compose 部署 nginx+...
文章浏览阅读1.3k次。5:再次启动nginx,可以正常启动,可以...
文章浏览阅读3.1w次,点赞105次,收藏182次。高性能:Nginx ...