加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 运营中心 > Nginx > 正文

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

发布时间:2020-12-13 21:01:38 所属栏目:Nginx 来源:网络整理
导读:我正在用PHP编写一个简单的CMS.页面(降价文件)和图像可以像这样(分别)访问: example.org/?q=about.mdexample.org/?i=photo.jpg 或者,我想使用带有Nginx的干净URL,使相同的请求看起来像这样: example.org/aboutexample.org/photo.jpg 我宁愿使用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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读