apache - 强制 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.br
或www.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]
解决方案
您的代码会生成一个重定向循环。此外,您不需要转义目标上的斜线。
您可以合并虚拟主机块中的所有内容(比使用 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]
推荐阅读
- java - 如何使用 SNMP4J 在 OID / Managed Object 上注册侦听器以执行设置或获取代理接收的请求?
- ios - 无法对 com.mydomain.demoapp 执行操作“Promote”,因为它当前不受支持
- python - 有没有办法在 matplotlib 中正确放置重叠的描述框?
- sql-server - 尝试添加迁移时,SQL 中缺少迁移数据
- corda - java.lang.NoClassDefFoundError 与外部库
- docker - 如果没有在 docker run -v 中指定 host-src 是什么
- json - 从 JSON 中获取键名
- wpf - 如何根据需要填充矩形
- javascript - 具有自动宽度的 Slick Slider 单行
- css - 角垫扩展面板,文本太长,不适合