需求:localhost/ey3i → localhost/responseShortUrl.php?url=ey3i,ey3i 為 4-7 位大小寫字母數字。
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` 會合併)。$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` 中配置目錄權限)。