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

前端之家收集整理的这篇文章主要介绍了php – Nginx清理网址,如何使用try_files将文件夹重写为参数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

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

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

  1. example.org/about
  2. example.org/photo.jpg

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

  1. location / {
  2. try_files $uri $uri/ /?q=$uri.md =404;
  3. }
  4. location ~ \.(gif|jpg|png)${
  5. try_files $uri /?i=$uri =404;
  6. }

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

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

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

  1. server_name example.org;
  2. root /srv/example/;
  3. index index.html index.htm index.PHP;
  4. (...)
  5. location ~ \.PHP${
  6. fastcgi_split_path_info ^(.+\.PHP)(/.+)$;
  7. fastcgi_pass unix:/var/run/PHP5-fpm.sock;
  8. fastcgi_index index.PHP;
  9. include fastcgi.conf;
  10. }

和fastcgi.conf也是标准的.

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

  1. location / {
  2. try_files $uri $uri/ /?q=$uri.md;
  3. }
  4. location ~ \.(gif|jpg|png)${
  5. try_files $uri /?i=$uri;
  6. }

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

猜你在找的Nginx相关文章