You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 like l=en. The regex ^l=([a-z]{2})$ captures the two-letter language code, and we redirect to /%1/ (where %1 is the captured language code). Using R=301 makes this a permanent redirect (great for SEO), but you can use R=302 temporarily 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 (!-f and !-d). Then we capture the two-letter language code from the URL path and internally forward the request to index.php?l=$1. The QSA flag 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_rewrite is 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=302 first: Once you confirm everything works as expected, switch back to R=301 for permanent redirects.

内容的提问来源于stack exchange,提问作者majimekun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:25:19