Home  >  Article  >  Backend Development  >  Introduction to the method of realizing page staticization in PHP (code example)

Introduction to the method of realizing page staticization in PHP (code example)

不言
不言forward
2019-01-09 10:17:042267browse

本篇文章给大家带来的内容是关于PHP实现页面静态化的方法介绍(代码示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

最近在工作中需要实现页面静态化,借此机会把相关资料记录,整理成demo。具体需求为输入域名,如baidusina等,如有静态页,返回静态页;如没有,访问获取网页内容并生成静态页。

页面静态化的好处

根据不同情况,有些需要生成静态页,有些实现伪静态即可,根据实际需求进行抉择。而静态化的好处,总结下来有以下几点:

  • 提高访问速度

  • 减少服务器压力

  • 有利于SEO

  • 提升网站稳定性

PHP生成静态页

PHP生成静态页有多种方法,此次使用的是ob系列函数,函数内容可查看手册。


Rewrite重写规则

在.htaccess中实现Rewrite重写规则,至于使用.htaccess是否影响效率不在讨论范围之内。

RewriteEngine on
# 如果有符合条件的静态页,返回静态页
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
# 路由重写
RewriteRule ^(\w+).html$ /index.php?website=$1

测试

此时访问域名www.youWebsite.com/baidu.html,由于没有静态页,相当于请求到www.youWebsite.com/index.php?website=baidu。通过PHP的处理,已经生成baidu.html文件。
再次访问www.youWebsite.com/baidu.html,这时由于存在baidu.html文件,直接返回静态页,而不再请求PHP。有几点注意事项:

  • 检查apache是否开启Rewrite

  • Linux下文件权限

The above is the detailed content of Introduction to the method of realizing page staticization in PHP (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete