【问题标题】:Nginx clean urls, how to rewrite a folder as an argument with try_filesNginx clean urls,如何使用try_files将文件夹重写为参数
【发布时间】:2015-06-18 20:59:08
【问题描述】:

我正在用 PHP 编写一个简单的 CMS。页面(markdown 文件)和图像的访问方式如下(分别):

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

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

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

我宁愿使用try_files 而不是ifrewrite,但经过几个小时的试验,我无法让它工作。

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

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

我不明白为什么上面的代码不起作用(带参数的网址可以正常工作,但漂亮的网址会出现 404 错误)。

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


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

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 也是标准的。

【问题讨论】:

  • document_root 设置是否正确?您可以在try_files 中尝试/index.php?q=$uri.md,即明确声明index.php,尽管我认为它应该像这样工作。
  • 我很确定document_root 没问题,因为常规/长网址可以正常工作。我也尝试过/index.php?q=$uri.md,但没有任何区别。

标签: php nginx url-rewriting uri


【解决方案1】:

只需省略=404,我就能让您的示例正常工作:

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

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

引用the manual:

按指定顺序检查文件是否存在,并使用第一个找到的文件进行请求处理; [...] 如果没有找到任何文件,则会进行内部重定向到最后一个参数中指定的uri

您想要内部重定向,只有在没有找到任何文件时才会发生这种情况,但总是找到 =404

【讨论】:

  • 太好了,现在可以完美运行了!并重新阅读您的答案,我什至了解其背后的逻辑。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-29
  • 1970-01-01
  • 2021-09-07
  • 1970-01-01
  • 2015-01-07
  • 2020-04-07
相关资源
最近更新 更多