微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.

原文地址:https://www.jb51.cc/nginx/434821.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐