通过.htaccess改造单语言项目为多语言,修复产品页路由并保留参数
多语言项目URL重写规则调整方案
问题概述
需将单语言项目改造为多语言项目,调整URL结构以支持语言前缀(如it、es),现有规则无法处理/it/store/product-with-nice-url这类产品详情页请求,需修正规则同时保留查询参数。
原URL结构
www.site.com www.site.com/contact.php www.site.com/store/ -> 全产品列表页 www.site.com/store/product-with-nice-url -> 单个产品页
期望多语言URL结构
www.site.com/it/ www.site.com/it/contact.php www.site.com/it/store/ -> 全产品列表页 www.site.com/it/store/product-with-nice-url -> 单个产品页
现有.htaccess规则
AddDefaultCharset utf-8 DirectoryIndex index.php Options -Indexes RewriteCond %{HTTP_HOST} !^www\. [NC] RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301] # Loads single file in the root RewriteCond %{DOCUMENT_ROOT}/$2/index.php -f RewriteRule ^([a-z]{2})/(.*?)/?$ $2/index.php?lang=$1 [L] RewriteCond %{DOCUMENT_ROOT}/$2 -f RewriteRule ^([a-z]{2})/(.+) $2?lang=$1 [L]
当前问题
现有规则仅能处理根目录文件(如contact.php)和/it/store/这类目录索引页,无法匹配/it/store/product-with-nice-url这类产品详情页,同时原规则未保留查询参数(如/it/store/?category=2&make=Sony&page=2)。
调整后的.htaccess规则
AddDefaultCharset utf-8 DirectoryIndex index.php Options -Indexes # 强制跳转至www域名 RewriteCond %{HTTP_HOST} !^www\. [NC] RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301] # 处理带语言前缀的store子路径(含产品详情页) RewriteRule ^([a-z]{2})/store/(.*)$ store/index.php?lang=$1&path=$2 [QSA,L] # 处理带语言前缀的目录索引页(如/it/、/it/store/) RewriteCond %{DOCUMENT_ROOT}/$2/index.php -f RewriteRule ^([a-z]{2})/(.*?)/?$ $2/index.php?lang=$1 [QSA,L] # 处理带语言前缀的根目录文件(如/it/contact.php) RewriteCond %{DOCUMENT_ROOT}/$2 -f RewriteRule ^([a-z]{2})/(.+) $2?lang=$1 [QSA,L]
规则说明
- 强制www跳转:维持原有逻辑,确保所有请求统一到www域名下。
- store子路径规则:优先匹配带语言前缀的
store下所有路径,将请求转发至store/index.php,传递语言参数lang和产品路径参数path;QSA标记自动保留原URL的查询参数(如category、page等)。 - 目录索引页规则:保留原有匹配逻辑,新增
QSA标记确保查询参数不丢失。 - 根目录文件规则:添加
QSA标记,支持带参数的根目录文件请求(如/it/contact.php?foo=bar)。
内容的提问来源于stack exchange,提问作者Europeuser
相关产品推荐
相关产品推荐

