将非 www 重定向到 www 添加 URL 查询字符串

Redirect non-www to www adding URL query string

我使用 .htaccess 在我的 opencart 上使用 SEO URL,现在我想将所有非 www URL 访问重定向到带有 www 的 URL。所以我在我的 .htaccess 文件中添加了这些行:

RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/ [R=301,L]

是的,现在如果 URL 在我的域名前没有写 www,它总是被重定向到 www,但我发现了一些我认为不应该出现在 URL 中的东西。

当我转到 www.mydomain.com/category 时,我试图通过删除 www 来测试 URL(因此它变成了 mydomain.com/category)并点击 ENTER。 URL 被重定向到 www.mydomain.com/index.php?_route_=category。我不知道是什么让 URL 变成这样,我认为 URL 应该重定向到 www.mydomain.com/category。我试图在这一行之前和之后移动重定向行的位置:

RewriteRule ^([^?]*) index.php?_route_= [L,QSA]

这里是完整的.htaccess内容:

RewriteBase /

RewriteRule ^sitemap.xml$ index.php?route=feed/google_sitemap [L]
RewriteRule ^googlebase.xml$ index.php?route=feed/google_base [L]
RewriteRule ^download/(.*) /index.php?route=error/not_found [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !.*\.(ico|gif|jpg|jpeg|png|js|css)
RewriteRule ^([^?]*) index.php?_route_= [L,QSA]

# Redirect non-www to www (I have tried to move this lines but still resulting the same)
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/ [R=301,L]

我的重定向行有什么问题?任何帮助和建议将不胜感激。谢谢。

问题是您将域的重写设置得太低了。将其移动到 RewriteBase / 之后,它将在 url 重写 do

之前执行
RewriteBase /
# Redirect non-www to www (I have tried to move this lines but still resulting the same)
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/ [R=301,L]

RewriteRule ^sitemap.xml$ index.php?route=feed/google_sitemap [L]
RewriteRule ^googlebase.xml$ index.php?route=feed/google_base [L]
RewriteRule ^download/(.*) /index.php?route=error/not_found [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !.*\.(ico|gif|jpg|jpeg|png|js|css)
RewriteRule ^([^?]*) index.php?_route_= [L,QSA]