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

Apache .htaccess 短網址重寫:RewriteRule 正則捕獲 4-7 位字母數字

     編輯:程式設計綜合問答

需求:localhost/ey3i → localhost/responseShortUrl.php?url=ey3i,ey3i 為 4-7 位大小寫字母數字。

.htaccess 完整配置

RewriteEngine On
RewriteBase /

# 排除真實存在的文件/目錄(圖片、CSS、JS 等)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# 匹配 4-7 位字母數字,捕獲至 $1
RewriteRule ^([A-Za-z0-9]{4,7})$ responseShortUrl.php?url=$1 [L,NC,QSA]

標誌位解析

  • L (Last):匹配後停止後續規則。
  • NC (NoCase):大小寫不敏感。
  • QSA (QueryStringAppend):保留原查詢字符串(如 `?foo=bar` 會合併)。

PHP 端獲取

$shortCode = $_GET['url'] ?? '';
if (preg_match('/^[A-Za-z0-9]{4,7}$/', $shortCode)) {
    // 查詢數據庫還原長網址
    header("Location: $longUrl", true, 301);
    exit;
}
http_response_code(404);
echo "Short code not found";

常見坑

  • 未開啟 AllowOverride All 導致 .htaccess 不生效(需在 `httpd.conf` / `apache2.conf` 中配置目錄權限)。
  • 規則順序靠前,避免被通用規則(如前端路由 fallback)攔截。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved