不懂就问系列: PHP 网站使用 nginx 遇到的一些问题

2020-10-19 13:07:13 +08:00
 Ethson

准备使用 php 做个网站,域名是 dev.hellotools.org,根目录下有四个文件,分别是,

  1. index.php,就是主页了
  2. about.php,关于页面
  3. 404.php,也就是 404 页面了
  4. /a/b/page.php,a 和 b 是目录,意思就是根目录下有个二级目录,里边有个 page.php

现在我想实现以下功能,

  1. 访问 dev.hellotools.org 时,浏览器上地址栏显示 dev.hellotools.org,且浏览器显示 index.php 的内容;
  2. 访问 dev.hellotools.org/about 时,浏览器上地址栏显示 dev.hellotools.org/about,且浏览器显示 about.php 的内容;
  3. 访问 dev.hellotools.org/nono 时,浏览器上地址栏显示 dev.hellotools.org/nono,且浏览器显示 404.php 的内容;
  4. 访问 dev.hellotools.org/a/b/page 时,浏览器上地址栏显示 dev.hellotools.org/a/b/page,且浏览器显示 /a/b/page.php 的内容

于是我的 nginx 配置如下,

server
    {
        listen 80;
        server_name  dev.hellotools.org;

        index index.html index.htm index.php default.html default.htm default.php;
        root  /home/wwwroot/dev.hellotools.org;

        charset utf-8;

        error_page 404 /404.php;

        ## enable php path info
        location ~ [^/]\.php(/|$)
        {
            fastcgi_pass  unix:/tmp/php-cgi.sock;
            fastcgi_index index.php;
            include fastcgi.conf;
            include pathinfo.conf; 
        }

        location / {
            try_files $uri $uri.php /index.php;
        }
    }

搞不清楚我的配置哪里有问题,在访问 about 页面的时候,竟然文件直接下载了,404 也出不来,不知道哪里出问题了。

每个页面的内容都写清楚了,就几个简单的汉字和字母。比如你打开的是 index.php,那么页面内容就有:index.php。其它都是类似的。

折腾一晚上了,实在找不出了,望有了解的大兄弟指点一下。

1943 次点击
所在节点    程序员
8 条回复
dilu
2020-10-19 13:27:28 +08:00
```
try_files $uri $uri.php /$url.php;
```

试试?
dilu
2020-10-19 13:31:09 +08:00
try_files $uri $uri/ /$url.php;

如果还是不行试试这个
zjsxwc
2020-10-19 13:55:26 +08:00
仅仅只是去掉.php 后缀的话

```
location / {
try_files $uri $uri.html $uri/ @extensionless-php;
index index.html index.htm index.php;
}
location @extensionless-php {
rewrite ^(.*)$ $1.php last;
}
```
Ethson
2020-10-19 14:06:02 +08:00
@dilu 你的第二个答案是对的。

@zjsxwc 你的答案也是对的。

非常感谢两位。只是 @dilu 提供的正确答案有些不太明白,为什么要加上 **$uri/**,这不是在目录下查找的嘛,但我这里没有这个目录啊,去找也没用啊,既然是无用功,那为什么去做呢?不得解....
Lax
2020-10-19 14:09:13 +08:00
直接下载的问题,加一句 default_type text/html;
Ethson
2020-10-19 14:15:57 +08:00
@Lax 谢谢,学到了。
brader
2020-10-19 14:18:24 +08:00
@Ethson 你理解有误,你仔细琢磨 try_files 的用法,其实我想,$uri/没有起作用,因为它正如你想的一样,没找到,所以继续执行后面一句,起作用的是后面一句 /$url.php ,
至于你一开始,填了$uri.php ,问题就在这里了,nginx 找到了改文件,所以 nginx 的 try_files 会将该文件发送给用户。
Hanada
2020-10-19 14:18:50 +08:00
@Ethson 优先查找是否存在该路径,不存在才去找.php 文件。也就是如果同时有一个 test 文件夹和 test.php ,会优先匹配到 test 文件夹而不是 test.php

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://tanronggui.xyz/t/716355

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX