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

Apache + PHP (DedeAMPZ) 偽靜態配置指南:mod_rewrite 啟用與 .htaccess 範例

     編輯:PHP 相關知識

前言

DedeAMPZ 等 PHP 整合包預設可能未啟用 mod_rewrite,導致偽靜態 (URL Rewrite) 失效。本文提供 Apache 配置修正步驟與常用 .htaccess 規則。

步驟一:啟用 mod_rewrite 模組

編輯 httpd.conf (或 apache2.conf):

# 取消註解
LoadModule rewrite_module modules/mod_rewrite.so

步驟二:允許目錄覆蓋

在對應 <Directory> 區塊設定 AllowOverride All:

<Directory "C:/DedeAMPZ/Apache/htdocs">  # 或 /var/www/html
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

重啟 Apache:httpd -k restart 或 systemctl restart httpd。

步驟三:編寫 .htaccess 規則 (專案根目錄)

RewriteEngine On
RewriteBase /

# 排除實體存在的檔案/目錄
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# 統一入口 (如 MVC 框架)
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

# 或針對特定 CMS (如 Dedecms)
# RewriteRule ^(.*)/list-([0-9]+)\.html$ $1/list.php?tid=$2 [L]
# RewriteRule ^(.*)/view-([0-9]+)-1\.html$ $1/view.php?aid=$2 [L]

常見問題排查

  1. 500 Internal Server Error:.htaccess 語法錯誤,檢查 Apache error_log。
  2. 規則不生效:確認 AllowOverride All 生效、mod_rewrite 已載入 (phpinfo() 查看 Loaded Modules)。
  3. 循環重導向:規則匹配到自身,加入 RewriteCond %{REQUEST_URI} !^/index\.php 排除。
  4. 靜態資源 404:確保 RewriteCond %{REQUEST_FILENAME} !-f 在規則之前。

Nginx 環境對應配置

location / {
    try_files $uri $uri/ /index.php?$query_string;
}

# Dedecms 典型規則
rewrite ^/(.*)/list-([0-9]+)\.html$ /$1/list.php?tid=$2 last;
rewrite ^/(.*)/view-([0-9]+)-1\.html$ /$1/view.php?aid=$2 last;

總結

偽靜態核心三步:LoadModule rewrite_module、AllowOverride All、編寫正確 .htaccess。DedeAMPZ 只需修改 httpd.conf 對應目錄區塊並重啟即可。生產環境建議將規則直接寫入 httpd.conf <Directory> 區塊 (效能更好、避免 .htaccess 讀取開銷)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved