Apache mod_rewrite 是 Apache HTTP Server 中的一个富强模块,它容许你利用规矩来修改恳求的 URL,从而实现 URL 重写、暗藏实在道路、创建友爱的 URL 等功能。以下将具体介绍 mod_rewrite 的设置跟利用方法,并经由过程现实案例停止剖析。
在开端设置之前,起首须要确认你的 Apache 效劳器能否曾经启用了 mod_rewrite 模块。
经由过程 PHP 供给的 phpinfo()
函数可能检查效劳器情况设置,包含已加载的 Apache 模块。
<?php
phpinfo();
?>
在浏览器中拜访此 PHP 文件,找到 “Loaded Modules” 部分,检查能否包含 “mod_rewrite”。
假如不找到 “mod_rewrite”,则须要手动启用该模块。
httpd.conf
。LoadModule
指令,找到 rewritemodule
相干的设置。#LoadModule rewritemodule modules/modrewrite.so
前面的 #
号去掉落。LoadModule rewritemodule modules/modrewrite.so
为了让 Apache 支撑目录级其余设置,须要修改 httpd.conf
文件,并创建 .htaccess
文件。
httpd.conf
文件。<Directory />
段落。AllowOverride None
修改为 AllowOverride All
。<Directory />
Options FollowSymLinks
AllowOverride All
</Directory>
在须要设置 URL 重写的目录下创建 .htaccess
文件。
RewriteEngine On
启用 rewrite 引擎。
RewriteEngine On
定义 URL 重写规矩。
RewriteRule ^oldpath/$ newpath/ [L]
^oldpath/$
:婚配以 oldpath/
扫尾的道路。newpath/
:重写后的道路。[L]
:结束进一步处理。定义 rewrite 规矩的前提。
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
!-f
:文件不存在。!-d
:目录不存在。RewriteEngine On
RewriteRule ^product/([a-zA-Z0-9]+)/$ product.php?id=$1 [L]
这个规矩将 /product/12345/
转换为 /product.php?id=12345
。
RewriteEngine On
RewriteRule ^(.*)\.html$ $1.php [L]
这个规矩将 .html
文件转换为 .php
文件,比方 /index.html
转换为 /index.php
。
经由过程以上介绍,信赖你曾经对 Apache mod_rewrite 有了必定的懂得。在现实利用中,可能根据须要编写响应的 rewrite 规矩,实现 URL 重写、暗藏实在道路等功能。