如何通过.htaccess将带查询字符串的index.php流量重定向至指定路径
Alright, let's solve this redirect problem exactly as you need it. The core requirement is to only redirect domain.com/index.php requests that have either a query string (like ?topic=11841.0) or path info (like /board,200.0.html) to domain.com/forum/index.php, while keeping all other site traffic unaffected. Below are solutions for the two most common web servers:
Apache (using mod_rewrite)
Add these rules to your .htaccess file (or server config) in the root directory of domain.com:
RewriteEngine On # Redirect index.php with query string OR path info to /forum/index.php RewriteCond %{REQUEST_URI} ^/index\.php$ RewriteCond %{QUERY_STRING} .+ [OR] RewriteCond %{REQUEST_URI} ^/index\.php/.+ RewriteRule ^index\.php(.*)$ /forum/index.php$1 [R=302,L]
Rule Breakdown:
RewriteEngine On: Enables mod_rewrite functionality.- First
RewriteCond: Ensures we're only targeting requests exactly for/index.php. - Second
RewriteCond: Checks if there's a non-empty query string (.+means at least one character). The[OR]connects it to the next condition. - Third
RewriteCond: Catches requests where/index.phphas additional path info (like/board,200.0.htmlappended). RewriteRule: Maps the original/index.php(plus any path info) to/forum/index.php, preserving the query string automatically. UseR=301instead of302once you've tested the redirect works correctly (for permanent redirects).
Nginx
Add this configuration inside your server block for domain.com:
server { server_name domain.com; # Handle targeted redirect for index.php location = /index.php { # Redirect if there's a query string if ($query_string != "") { return 302 /forum/index.php$is_args$args; } # Redirect if there's path info appended to index.php if ($request_uri ~* ^/index\.php/.+) { rewrite ^/index\.php(/.*)$ /forum/index.php$1 redirect; } # Allow normal access to index.php with no query string/path info try_files $uri $uri/ =404; } # Add your other site configurations here (e.g., PHP processing, static files) }
Config Breakdown:
location = /index.php: Exact match for requests to/index.php.- First
ifblock: Triggers a redirect if the query string isn't empty.$is_argsadds a?only if there are arguments, and$argspreserves the original query string. - Second
ifblock: Uses a regex to match/index.phpwith appended path info, then rewrites the URL to include that path info in the/forum/version. try_files: Lets requests to/index.phpwith no extra data pass through normally (no redirect).
Note: Use permanent instead of redirect in the rewrite rule (or 301 instead of 302 in the return statement) once you've verified the redirect behaves as expected.
内容的提问来源于stack exchange,提问作者Raveen W

