首页 > 解决方案 > 强制 www 并重定向根目录

问题描述

我找不到能回答我的问题,或者我无法使用正确的术语进行搜索,但是来吧。我的 htaccess 中有以下规则:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^domain\.com\.br$ [OR]
RewriteCond %{HTTP_HOST} ^www\.domain\.com\.br$
RewriteRule ^(.*)$ "https\:\/\/www\.domain\.com\.br\/site" [R=301,L]

这在用户仅输入 URL(domain.com.brwww.domain.com.br)时有效,但是当用户以这种方式访问​​时我需要它重定向:

domain.com.br 或 www.domain.com.br --> https://www.domain.com.br/site
domain.com.br/XXX --> https://www.domain.com.br /XXX

我应该为此使用什么规则?

更新:服务器已经有一个强制 SSL 的默认规则,在这种情况下,没有必要把它放在 htaccess 中

规则更新:

**On virtual host:**
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP:X-Forwarded-Proto} !https [NC]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

**On htaccess file:**
RewriteCond %{HTTP_HOST} ^domain\.com\.br$ [OR]
RewriteCond %{HTTP_HOST} ^www\.domain\.com\.br$
RewriteRule ^/?$ https://www.domain.com.br/site/ [R=301,L]

标签: apache.htaccessmod-rewrite

解决方案


您的代码会生成一个重定向循环。此外,您不需要转义目标上的斜线。

您可以合并虚拟主机块中的所有内容(比使用 htaccess 更快):

RewriteEngine On

# force https
RewriteCond %{HTTPS} off [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# force www
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# redirect root directory to /site/
RewriteRule ^/?$ /site/ [R=301,L]

当然,您会看到一个重定向链,例如http://domain.tld/,因为它将首先重定向到https://domain.tld/然后到https://www.domain.tld/,最后到https://www.domain/tld/site/。这可以。但是,如果你真的想只用一个重定向来处理所有事情,你可以。但是,它将不那么通用。

例如,你最终会得到这些规则:

RewriteEngine On

# force root directory to /site/ (https+www)
RewriteRule ^/?$ https://www.domain.com.br/site/ [R=301,L]

# force any other pages to https+www if not the case already
RewriteCond %{HTTPS} off [NC,OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.domain.com.br%{REQUEST_URI} [R=301,L]

推荐阅读