Apache URL模式重定向:.htaccess(mod_rewrite)规则调试需求
Fixing Your mod_rewrite Redirect for /fix/ URLs
First, let's break down why your existing rule isn't doing what you need:
- Your current setup captures the path after
/fix/in%1, but theRewriteRule ^(.*)is matching the entire request URI (including/fix/), which creates unnecessary complexity here. - Most importantly, query parameters aren't being passed through—you haven't included the
QSAflag, so any?foo=barat the end of the original URL gets dropped entirely. - While
R=302works for testing, once you confirm the redirect behaves as expected, you might want to switch toR=301for permanent redirects (just remember to clear your browser cache after making that change).
Here's the corrected .htaccess code that handles both the path and query parameters correctly:
Options +FollowSymLinks RewriteEngine On # Redirect any URL starting with /fix/ to the subdomain, preserving path and query params RewriteRule ^fix/(.*)$ http://server.sample.com/fix1/fix2/$1 [R=302,NC,QSA,L]
Let's walk through each part:
^fix/(.*)$: This directly matches any request starting with/fix/, capturing everything after that into the$1variable. We don't need a separateRewriteCondhere—it's more efficient to handle the match in the rule itself.http://server.sample.com/fix1/fix2/$1: We append the captured path ($1) to the target URL, so something like/fix/test/pagebecomes/fix1/fix2/test/page.QSA: This critical flag ensures any query parameters from the original URL (like?id=123) are appended to the target URL. So/fix/test?foo=barbecomeshttp://server.sample.com/fix1/fix2/test?foo=bar.L: This tells mod_rewrite to stop processing further rules once this one matches, preventing unintended conflicts with other rules you might have in your.htaccess.NC: Keeps the match case-insensitive, so/FIX/Testwill redirect the same as/fix/test.
Quick Testing Tips:
If you're still running into issues:
- Confirm mod_rewrite is enabled on your server (you can check via
phpinfo()or reach out to your hosting provider if you're unsure). - Make sure your
.htaccessfile is in the root directory ofsample.com(not inside the/fix/subfolder). - Clear your browser cache before testing—old redirects can get cached and lead to confusing results.
内容的提问来源于stack exchange,提问作者Vahid
相关产品推荐
相关产品推荐

