Hello! 欢迎来到阿珏酱のBlog!

.htaccess伪静态规则


avatar
阿珏 2017-12-04 1.95k


Apache的 mod_rewrite是比较强大的,在进行网站建设时,可以通过这个模块来实现伪静态。

检测Apache是否开启mod_rewrite功能

可以通过php提供的phpinfo()函数查看环境配置,找到“Loaded Modules”,其中列出了所有apache2handler已经开启的模块,如果里面包括“mod_rewrite”,则已经支持,不再需要继续设置。
如果没有开启“mod_rewrite”,则打开目录 apache目录下的“/apache/conf/” ,找到 httpd.conf 文件,再找到“LoadModule rewrite_module”,将前面的”#”号删除即表示取用该功能。   
 如果没有查找到“LoadModule” 区域,可以在最后一行加入“LoadModule rewrite_module ,modules/mod_rewrite.so”(独占一行),之后重启apache服务器。
再通过phpinfo()函数查看环境配置就有“mod_rewrite”为项了.。

让apache服务器支持.htaccess

如何让自己的本地APACHE服务器支持:“htaccess”呢? 只需修改apache的httpd.conf设置就可以让 APACHE支持“.htaccess”了。打开 APACHE目录的CONF目录下的httpd.conf文件,找到: Options FollowSymLinks AllowOverride None 改为 Options FollowSymLinks AllowOverride All 就行了。

建立.htaccess 文件

建立.htaccess文件时要注意,不能直接建,方法是通过记事本中的另存为菜单,在文件名窗口输入:“.htaccess”,然后点击保存。

rewrite规则学习

RewriteEngine on #rewriteengine为重写引擎开关on为开启off为关闭 
RewriteRule ([0-9]{1,})$index.php?id=$1 在这里,RewriteRule是重写规则,是用正则表达式的句子,([0-9]{1,})表示由数字组成的,$表示结束标志,表示以数字结束!
如果要实现伪静态页面,规则如下: 
RewriteEngine on RewriteRule ([a-zA-Z]{1,})-([0-9]{1,}).html$index.php?action=$1&id=$2 
在为个正则表达式中,([a-zA-Z]{1,})-([0-9]{1,}).html$是规则,index.php?action=$1&id=$2是要替换的格式,$1代表第1括号匹配的值,$2代表第二个括号的值,如此类推!

以下是我博客的.htaccess

<IfModule mod_rewrite.c>  
RewriteEngine on  
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteRule ^post-([0-9]{1,}).html$ index.php?post=$1 
</IfModule>  

http强制转跳https的规则

RewriteEngine on
RewriteBase / 
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R=301]

发表评论

相关阅读