通过Htaccess重写查询字符串实现URL不变的内部跳转
Got it, let's get those rewrite rules sorted so your internal URL mapping works exactly as you need—keeping the browser's address bar unchanged while routing requests to the correct index.php endpoints. Here's the complete, working set of rules, plus a breakdown of what each part does:
Complete .htaccess Rewrite Rules
# Enable Rewrite Engine (required for all rewrite rules) RewriteEngine On # Rule for search page: domain.com/search/?q=query&p=2 → domain.com/index.php?search=query&page=2 RewriteCond %{QUERY_STRING} ^q=([^&]+)&p=([0-9]+)$ RewriteRule ^search/$ index.php?search=%1&page=%2 [L] # Rule for niche page: domain.com/niche/?q=weddings&p=2 → domain.com/index.php?group_name=weddings&page=2 RewriteCond %{QUERY_STRING} ^q=([^&]+)&p=([0-9]+)$ RewriteRule ^niche/$ index.php?group_name=%1&page=%2 [L] # Rule for tag page: domain.com/tag/?q=rings&p=2 → domain.com/index.php?tag=rings&page=2 RewriteCond %{QUERY_STRING} ^q=([^&]+)&p=([0-9]+)$ RewriteRule ^tag/$ index.php?tag=%1&page=%2 [L]
Key Details to Know
RewriteEngine On: This kicks off Apache's mod_rewrite module—make sure your server has this module enabled, otherwise none of these rules will work.RewriteCondLogic: Each condition checks that the query string follows the patternq=VALUE&p=NUMBER. The([^&]+)captures your search/niche/tag value (any character except&to avoid breaking parameter boundaries), and([0-9]+)captures the numeric page number.RewriteRuleMapping: The first part (^search/$,^niche/$,^tag/$) matches the exact URL path the user sees. The target rewrites the request internally toindex.phpwith your desired parameter names, using%1and%2to reuse the values we captured from the original query string.[L]Flag: This tells Apache to stop processing further rewrite rules once this one matches—prevents unintended conflicts with other rules you might have in your.htaccess.- No Redirect Flag: We intentionally skip the
[R]flag here because we want an internal server rewrite. This keeps the original user-facing URL visible in the browser while the server serves content fromindex.phpbehind the scenes.
内容的提问来源于stack exchange,提问作者Zheka
相关产品推荐
相关产品推荐

