Home  >  Article  >  php教程  >  Nginx下配置PHP的URL重写,实现PHP伪静态

Nginx下配置PHP的URL重写,实现PHP伪静态

WBOY
WBOYOriginal
2016-06-06 20:11:261490browse

最近在写一个PHP实现的URL压缩程序,其中最关键的地方就是URL的伪静态,能够让xxx.com/111 这样的页面不出现404错误,而是达到预期的转换效果。 如果使用纯php,估计最多只能实现xxx.com/index.php/111,要更精简必须操作Nginx或Apach的重写,本文只介绍Ngin

最近在写一个PHP实现的URL压缩程序,其中最关键的地方就是URL的伪静态,能够让xxx.com/111 这样的页面不出现404错误,而是达到预期的转换效果。

如果使用纯php,估计最多只能实现xxx.com/index.php/111,要更精简必须操作Nginx或Apach的重写,本文只介绍Nginx的方法。

在Nginx中打开相应的.conf文件,一般位于/usr/local/nginx/conf/vhost。

在其中加入以下代码:

location?/? ??
{? ??
????if?(!-f?$request_filename){? ??
????????set?$rule_0?1$rule_0;? ??
????}? ??
????if?(!-d?$request_filename){? ??
????????set?$rule_0?2$rule_0;? ??
????}? ??
????if?($rule_0?=?"21"){? ??
????????rewrite?^/([0-9A-Za-z]+)/?$?/index.php?i=$1?last;? ??
????}? ??
}??

以上代码的功能是,将 xxx.com/ 后面的所有数字、大小写字母,直接重写到 index.php?i= 后面的内容。例如,输入 xxx.com/fuck 将会自动变成 xxx.com/index.php?i=fuck 。对倒数第三行的代码做适当修改,再配合PHP的_GET函数,成功实现URL伪静态。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn