nginx php伪静态规则,实现访问不存在的html文件指向php文件

nginx中try_files的的作用一般用户url的美化:

location / {
            try_files $uri $uri/ /index.php?$query_string;
}
location ~ .*\.(php|php5)?$
{
            fastcgi_pass  127.0.0.1:9000;
            fastcgi_index index.php;
}

当用户请求 http://localhost/example.html?p=222 时,这里的 u r i 就 是 / e x a m p l e 。 t r y f i l e s 会 到 硬 盘 里 尝 试 找 这 个 文 件 。 如 果 存 在 名 为 / uri 就是 /example。 try_files 会到硬盘里尝试找这个文件。如果存在名为 / uri/exampletryfiles/root/example(其中 $root 是项目代码安装目录)的文件,就直接把这个文件的内容发送给用户。
显然,目录中没有叫 example 的文件。然后就看 u r i / , 增 加 了 一 个 / , 也 就 是 看 有 没 有 名 为 / uri/,增加了一个 /,也就是看有没有名为 / uri///root/example/ 的目录。
又找不到,就会 fall back 到 try_files 的最后一个选项 /index.php,发起一个内部 “子请求”,也就是相当于 nginx 发起一个 HTTP 请求到 http://localhost/index.php。
这个请求会被 location ~ .*.(php|php5)?$ { … } catch 住,也就是进入 FastCGI 的处理程序。而具体的 URI 及参数是在 REQUEST_URI 中传递给 FastCGI 和 PHP 程序的,因此不受 URI 变化的影响。

其中 $query_string 就是 p=222
最终这条规则的意思是
如果用户请求了一个不存在的文件(example.html)时候,内部重定向到index.php 并携带参数
结果相当于: http://localhost/example.php?p=222

猜你喜欢

转载自blog.csdn.net/Sncdma/article/details/108352411