首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

Apache mod_rewrite 实现 PHP 伪静态:从开启模块到 .htaccess 规则实战

     編輯:PHP 綜合知識

步骤 1:确认并开启 mod_rewrite

<?php phpinfo(); ?>

搜索 Loaded Modules,若无 mod_rewrite:

  1. 打开 httpd.conf
  2. 找到 #LoadModule rewrite_module modules/mod_rewrite.so 去掉 #
  3. 或在末尾添加 LoadModule rewrite_module modules/mod_rewrite.so
  4. 重启 Apache,再次 phpinfo() 验证

步骤 2:允许 .htaccess 覆盖

<Directory "D:/wwwroot">
    Options FollowSymLinks
    AllowOverride All  # 原为 None
</Directory>

步骤 3:创建 .htaccess 文件

记事本 “另存为” → 文件名 .htaccess(含前导点)。

步骤 4:Rewrite 规则语法速成

RewriteEngine On
# 简单数字 ID 映射
RewriteRule ^([0-9]+)$ index.php?id=$1 [L]

# 伪静态:page-18.html → index.php?action=page&id=18
RewriteRule ^([a-zA-Z]+)-([0-9]+)\.html$ index.php?action=$1&id=$2 [L]
  • [L] 最后一条规则
  • $1、$2 对应正则捕获组

测试脚本 index.php

<?php
echo 'Action: ' . ($_GET['action'] ?? 'N/A') . '
'; echo 'ID: ' . ($_GET['id'] ?? 'N/A'); ?>

访问 https://localhost/page-18.html 输出:

Action: page
ID: 18

进阶:虚拟主机 + hosts 实现本地域名

# httpd-vhosts.conf
<VirtualHost *:80>
    ServerName localhost.www.dz.cn
    DocumentRoot "d:/wamp/www/dz"
</VirtualHost>
# C:\Windows\System32\drivers\etc\hosts
127.0.0.1 localhost.www.dz.cn

重启 Apache,浏览器访问 https://localhost.www.dz.cn 即生效。

常见坑

  • 正则未转义 . 导致匹配异常
  • 规则顺序:具体规则在前,通用规则在后
  • RewriteBase /subdir/ 处理子目录项目
  • 调试开启 RewriteLog / RewriteLogLevel(Apache 2.4 用 LogLevel alert rewrite:trace3)
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved