使用.htaccess重写含两个参数的URL(基于XAMPP环境)
Hey there! Let's get those redirects working exactly how you need them. Your current rule handles simple single-path URLs fine, but we need to tweak things to support the ID parameter case. Here's how to do it step by step:
1. Enable Rewrite Functionality First
Start by adding this line at the top of your .htaccess file (located in the public_html directory) to turn on Apache's rewrite engine:
RewriteEngine On
2. Handle the ID-Based URL Pattern First
Rewrite rules match from top to bottom, so we need to tackle the more specific page/id pattern before the general single-page rule. Add this rule:
# Redirect /about/1 to index.php?page=about&id=1 RewriteRule ^([a-z0-9_-]+)/(\d+)$ index.php?page=$1&id=$2 [L,QSA]
^([a-z0-9_-]+): Matches your page name (supports letters, numbers, underscores, and hyphens)/(\d+)$: Targets the numeric ID at the end of the URL[L]: Tells Apache this is the final rule to apply if matched (prevents conflicting with other rules)[QSA]: Preserves any extra query parameters you might pass (e.g.,/about/1?foo=barbecomesindex.php?page=about&id=1&foo=bar)
3. Set Up Simple Single-Page Redirects
Next, add the rule for your first requirement (and other basic pages like /abc):
# Redirect /home to index.php?page=home RewriteRule ^([a-z0-9_-]+)$ index.php?page=$1 [L,QSA]
This replaces your original (.*) rule with a more precise pattern that won't interfere with the ID-based URLs.
4. Double-Check Apache Configuration
Make sure your XAMPP Apache config (typically in xampp/apache/conf/httpd.conf) allows .htaccess overrides for your public_html directory. Look for this section and update AllowOverride to All:
<Directory "path/to/your/public_html"> AllowOverride All Require all granted </Directory>
Restart Apache after making this change to activate the setting.
Test It Out
- Visit
your-domain/home→ Should loadindex.php?page=home - Visit
your-domain/about/1→ Should loadindex.php?page=about&id=1 - Visit
your-domain/abc→ Still works as before, loadingindex.php?page=abc
内容的提问来源于stack exchange,提问作者Damodar Bhattarai

