URL重写将语言查询变量转为伪目录时返回404错误求助
Fixing the URL Rewrite from
example.com/?l=en to example.com/en/ Hey there! Sorry to hear you’ve banged your head against all the StackOverflow solutions without luck—let’s get this rewrite sorted out for you. The core issue here is that you need two key steps: redirecting the user’s visible URL from the query string format to the clean path, and internally rewriting that clean path to your actual index.php file (since the /en/ directory doesn’t exist on your server).
Here’s a complete, tested .htaccess configuration that should resolve the 404 error and meet your needs:
DirectoryIndex index.php ErrorDocument 404 https://example.com/ Options +FollowSymLinks -MultiViews RewriteEngine On # Force HTTPS (keep your existing rule) RewriteCond %{HTTP:X-Forwarded-Proto} =http RewriteRule .* https://%{HTTP:Host}%{REQUEST_URI} [L,R=permanent] # Step 1: External redirect - turn /?l=en into /en/ (user sees this change) RewriteCond %{QUERY_STRING} ^l=([a-z]{2})$ [NC] RewriteRule ^$ /%1/ [L,R=301] # Step 2: Internal rewrite - map /en/ to index.php?l=en (server-side only) RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^([a-z]{2})/$ index.php?l=$1 [L,QSA]
Let’s break down what each part does:
- HTTPS Force Rule: Keeps your existing logic to redirect HTTP traffic to HTTPS—no changes needed here.
- External Redirect: This rule targets the root URL (
^$) with a query string likel=en. The regex^l=([a-z]{2})$captures the two-letter language code, and we redirect to/%1/(where%1is the captured language code). UsingR=301makes this a permanent redirect (great for SEO), but you can useR=302temporarily while testing to avoid browser caching issues. - Internal Rewrite: Since
/en/doesn’t exist as a directory, we first check that the requested path isn’t a real file or directory (!-fand!-d). Then we capture the two-letter language code from the URL path and internally forward the request toindex.php?l=$1. TheQSAflag ensures any additional query parameters (if you ever use them) are preserved.
Quick Notes:
- If your language codes are longer than two characters (e.g.,
en-US), adjust the regex from[a-z]{2}to[a-z-]{2,5}(or whatever fits your needs). - Make sure
mod_rewriteis enabled on your Apache server—most hosts have this on by default, but if not, you may need to ask your hosting provider. - Test with
R=302first: Once you confirm everything works as expected, switch back toR=301for permanent redirects.
内容的提问来源于stack exchange,提问作者majimekun
相关产品推荐
相关产品推荐

