[英]Redirect subdomains + http to https using mod_rewrite in Apache Virtual Host
我有一個具有 1 個名稱和 2 個別名的虛擬主機name.domain.com.br
, alias1.domain.com.br
和alias2.domain.com.br
我需要將別名1
和2
重定向到name
,但它不能完全工作,這是我當前的代碼:
ServerName name.domain.com.br
ServerAlias alias1.domain.com.br
ServerAlias alias2.domain.com.br
DocumentRoot ****************
ErrorLog ****************
CustomLog ****************
RewriteEngine on
RewriteCond %{SERVER_NAME} =alias1.domain.com.br [OR]
RewriteCond %{SERVER_NAME} =alias2.domain.com.br [OR]
RewriteRule ^/(.*)$ https://name.domain.com.br [L,R=301]
However, this way the redirecting is only working when using http://aliasX.domain.com.br
and for some reason it puts two slashes at the end of the link, getting https://name.domain.com.br//
。 使用https://
時不起作用。
我希望所有有或沒有 https 的變體都重定向到https://name.domain.com.br
。
你能幫助我嗎?
RewriteCond %{SERVER_NAME} =alias1.domain.com.br [OR] RewriteCond %{SERVER_NAME} =alias2.domain.com.br [OR] RewriteRule ^/(.*)$ https://name.domain.com.br [L,R=301]
使用“https://”時不起作用。
HTTP 和 HTTPS 需要兩個單獨的虛擬主機容器。
毫無疑問,您已經將這些規則放在虛擬主機中,僅適用於 HTTP,例如。 <VirtualHost *:80>
。 您還需要在 HTTPS 的虛擬主機中重復重定向。 例如。 <VirtualHost *:443>
。 (盡管 HTTP vHost 中的重定向可以簡化,因為您只需要將所有內容重定向到 HTTPS - 請參閱下面的解決方案。)
但是,您發布的規則不正確。 由於最后一個條件( RewriteCond
指令)上的錯誤OR
標志,重定向總是會發生,實際上是無條件的。
您還丟棄了 URL 路徑並重定向到主頁? (瀏覽器更正了丟失的斜杠。)我認為這是一個錯誤,您應該將alias1.domain.com.br/foo
重定向到name.domain.com.br/foo
,而不是name.domain.com.br/
/C502D102EC550Zbr/C504?DA
出於某種原因,它在鏈接末尾添加了兩個斜杠
這不是由這個規則引起的。 一定有別的東西在這樣做。
所以,解決方案就變成了......
###
### HTTP (not secure)
###
<VirtualHost *:80>
ServerName name.domain.com.br
ServerAlias alias1.domain.com.br
ServerAlias alias2.domain.com.br
DocumentRoot ****************
ErrorLog ****************
CustomLog ****************
# Redirect everything to HTTPS and canonical domain
# No need for mod_rewrite, a simple mod_alias Redirect will suffice
Redirect 301 / https://name.domain.com.br/
</VirualHost>
###
### HTTPS (secure)
###
<VirtualHost *:443>
ServerName name.domain.com.br
ServerAlias alias1.domain.com.br
ServerAlias alias2.domain.com.br
DocumentRoot ****************
ErrorLog ****************
CustomLog ****************
# Other SSL directives here...
# Redirect to the canonical domain
RewriteEngine On
RewriteCond %{HTTP_HOST} !=name.domain.com.br [NC]
RewriteRule ^ https://name.domain.com.br%{REQUEST_URI} [R=301,L]
</VirualHost>
HTTPS
vHost 中的重定向檢查該請求是否尚未針對規范主機名,而不是檢查它是否是別名之一。
注意:檢查請求的主機名時,請使用HTTP_HOST
而不是SERVER_NAME
。 默認情況下它們是相同的,但是,根據服務器配置, SERVER_NAME
可能引用ServerName
指令的值,而不是客戶端請求的主機名。
您需要在測試之前清除瀏覽器緩存,因為任何錯誤的 301(永久)重定向都將被緩存。 首先使用 302(臨時)重定向進行測試,以避免潛在的緩存問題。
如上所述,如果您仍然在 URL 路徑的開頭看到雙斜杠,那么其他東西正在這樣做。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.