[英]how to redirect sub pages to www to non-www from htaccess
I am trying to redirect my subpage to a non-www but I get duplicate URLs of the same page.我正在尝试将我的子页面重定向到非 www,但我得到同一页面的重复 URL。
What I want to implement我想要实现的
https://www.example.com/category/webs => https://example.com/category/webs
http://example.com/category/webs => https://example.com/category/webs
http://www.example.com/category/webs => https://example.com/category/webs
.htaccess
.htaccess
Options -Indexes
RewriteEngine On
RewriteRule ^category/([a-zA-Z0-9-/]+) category-list.php?id=$1 [NC,L]
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^example\.com$
RewriteRule ^ https://example.com%{REQUEST_URI} [R=301,L]
</IfModule>
With this current code, my root domain redirects perfectly.使用此当前代码,我的根域可以完美重定向。 but not subpages!
但不是子页面! I read many articles but not helping
我读了很多文章但没有帮助
The rule you have posted already does this, but your rules are in the wrong order.您发布的规则已经这样做了,但是您的规则顺序错误。 You need to redirect the request before rewriting the request to
category-list.php
.在将请求重写为
category-list.php
之前,您需要重定向请求。 Otherwise, "subpages" will be redirected to category-list.php
, which is what I assume is happening.否则,“子页面”将被重定向到
category-list.php
,这是我假设正在发生的事情。
Aside: You should escape the literal hyphen in the character class ([a-zA-Z0-9-/]+)
, or move this to the start or end of the character class, to negate its special meaning.另外:您应该转义字符类
([a-zA-Z0-9-/]+)
中的文字连字符,或者将其移至字符类的开头或结尾,以否定其特殊含义。 You should also include the end-of-string anchor at the end of the regex, otherwise it will successfully match too much (potentially creating duplicate content).您还应该在正则表达式的末尾包含字符串结尾的锚点,否则它将成功匹配太多(可能会创建重复的内容)。
Try it like this instead:试试这样:
Options -Indexes
RewriteEngine On
# Canonical redirect
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^example\.com$
RewriteRule ^ https://example.com%{REQUEST_URI} [R=301,L]
# Rewrite request
RewriteRule ^category/([a-zA-Z0-9/-]+)$ category-list.php?id=$1 [NC,L]
No need to repeat the RewriteEngine
directive.无需重复
RewriteEngine
指令。 No need for the <IfModule>
wrapper.不需要
<IfModule>
包装器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.