Apache Rewrite URL失效:将查询参数URL转为友好路径URL
Let’s tackle your URL optimization issue step by step. There are two key adjustments needed in your Apache config to get this working properly:
1. Fix the IP-to-Domain Redirect to Preserve Path/Query Strings
Your current IP redirect rule discards any path or query string when redirecting from the IP to your domain. We need to update it to retain that information using the QSA (Query String Append) flag:
RewriteCond %{HTTP_HOST} ^33\.333\.33\.33$ RewriteRule ^(.*)$ https://xxxxx.com/$1 [L,R=301,QSA]
2. Add the Rule to Convert ? to / for the /imovel Path
To rewrite URLs like https://xxxxx.com/imovel?apartamento-cangaíba-são+paulo-73+m² to the friendly format, we need to target requests where:
- The request URI is exactly
/imovel - There’s a non-empty query string
Add this rule after your HTTPS redirect (it needs to run for HTTPS requests to the domain):
# Rewrite /imovel?query to /imovel/query (friendly URL) RewriteCond %{REQUEST_URI} ^/imovel$ RewriteCond %{QUERY_STRING} !^$ RewriteRule ^(.*)$ /$1/%{QUERY_STRING} [L,R=301,QSD]
Breakdown of the rule:
RewriteCond %{REQUEST_URI} ^/imovel$: Matches requests exactly to the/imovelpathRewriteCond %{QUERY_STRING} !^$: Ensures there’s a query string present to convertRewriteRule ^(.*)$ /$1/%{QUERY_STRING}: Rewrites the path to append the query string as a subpathQSD(Query String Discard): Removes the original query string from the rewritten URL (since we’ve moved it into the path)R=301: Marks this as a permanent redirect (ideal for SEO)L: Stops processing further rules once this one is applied
Fallback for Older Apache Versions (pre-2.4.0)
If your Apache version doesn’t support the QSD flag, replace the rewrite rule with this (the trailing ? discards the query string):
RewriteCond %{REQUEST_URI} ^/imovel$ RewriteCond %{QUERY_STRING} !^$ RewriteRule ^(.*)$ /$1/%{QUERY_STRING}? [L,R=301]
Full Updated Config
Putting it all together, your Apache SSL config should look like this:
RewriteEngine On # Redirect HTTP to HTTPS RewriteCond %{HTTPS} !on RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] # Rewrite /imovel?query to /imovel/query (friendly URL) RewriteCond %{REQUEST_URI} ^/imovel$ RewriteCond %{QUERY_STRING} !^$ RewriteRule ^(.*)$ /$1/%{QUERY_STRING} [L,R=301,QSD] # Redirect IP address to domain, preserving path/query strings RewriteCond %{HTTP_HOST} ^33\.333\.33\.33$ RewriteRule ^(.*)$ https://xxxxx.com/$1 [L,R=301,QSA] # Optional: Remove trailing slash (uncomment if needed) # RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME} !-d # RewriteRule ^(.*)/$ $1 [L,R=301]
Quick Tips:
- Test with
R=302(temporary redirect) first to avoid browser caching issues while you verify the setup works. Switch toR=301once everything is confirmed. - Ensure
mod_rewriteis enabled on your server (runa2enmod rewriteon Debian/Ubuntu systems if needed).
内容的提问来源于stack exchange,提问作者MagicHat

