使用 mod_rewrite 重定向循环

redirect loop with mod_rewrite

我正在尝试通过 mod_rewrite 向我的网页添加语言前缀 例如:

https://example.com/ > https://example.com/en/

并且在内部它需要翻译成`https://example.com/?language=en 我已经设法为基础 url 做到了,但是当我尝试使用其他一些暗示的重定向来做到这一点时,它总是以无限循环结束。 例如:

https://example.com/product-p-22.html > https://example.com/en/product-p-22.html

并在内部变成了`https://example.com/product_info.php?product_id=22&language=en 这是我的实际配置:

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} !^/(en|fr)/
RewriteCond %{REQUEST_URI} .(php|html) [OR]
RewriteCond %{REQUEST_URI} ^/$
RewriteCond %{QUERY_STRING} !language=
RewriteRule ^(.*)$ en/ [L,R=301]
RewriteCond %{REQUEST_URI} !^/example
RewriteRule ^(.*)/$ index.php?language=&%{QUERY_STRING}
RewriteRule ^(.*)/(.*)-p-(.*).html$ product_info.php?products_id=&language=&%{QUERY_STRING}

我尝试了很多标志,例如 L, END, DPI 或这些标志的组合,但没有成功。 当我查看调试日志时,似乎找到了正确的 url,但随后重新开始解析默认的 url:

pass through /var/www/example/product_info.php
init rewrite engine with requested uri /product-p-22.html
pass through /product-p-22.html

关于我在这里做错了什么?

Server version: Apache/2.4.41 (Ubuntu)

根据您显示的示例,您能否尝试以下操作。请确保在测试您的 URL 之前清除浏览器缓存。

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} !^en [NC]
RewriteRule ^(.*)$ en/ [NC,R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php?language=en [NC,QSA,L]

RewriteRule ^([^/]*)/([^-]*)-p-([^.]*)\.html$ product_info.php?products_id=&language=& [NC,L,QSA]

在您的站点根目录 .htaccess 中这样设置:

RewriteEngine On

RewriteCond %{THE_REQUEST} !\s/+(en|fr)/ [NC]
RewriteRule ^ /en%{REQUEST_URI} [NC,R=301,L]

RewriteRule ^([a-z]{2})/[^-/]+-p-([^./]+)\.html?$ product_info.php?language=&products_id= [L,QSA]

RewriteRule ^([a-z]{2})/$ index.php?language= [QSA,L]